You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python课程查询程序异常:输入课程号返回全部信息而非对应内容

问题修正方案

你的问题出在输出教室和时间时,直接打印了整个字典,而非通过输入的课程编号提取对应条目。

错误点说明

  • 原代码中print('Room:', rooms)直接输出了rooms字典的全部内容
  • print('Time:', times)同理,输出了times字典的全部内容
  • 正确逻辑应该像获取讲师信息那样,用输入的course作为键,从字典中取出对应的值

修正后的代码

def main():
    # Initialize dictionaries
    rooms = { 'CS101':3004, 'CS102':4501, 'CS103':6755,
                        'NT110':1244, 'CM241':1411}
    
    instructors = {'CS101':'Haynes', 'CS102':'Alvarado',
                                 'CS103':'Rich', 'NT110':'Burke',
                                 'CM241':'Lee'}
    times = {'CS101':'8:00 am', 'CS102':'9:00 am',
                     'CS103':'10:00 am', 'NT110':'11:00 am',
                     'CM241':'12:00 pm'}
    course = input('Enter a course number:' )
    
    if course not in rooms:
        print(course, 'is an invalid course number.')
    else:
        print('The details for course', course, 'are:')
        print('Room:', rooms[course])  # 修正:通过course索引获取对应教室
        print('Instructor:', instructors[course])
        print('Time:', times[course])  # 修正:通过course索引获取对应时间

# Call the main function.
main()

验证效果

输入有效课程号(例如CS101)后,会输出单条课程的对应信息:

Enter a course number:CS101
The details for course CS101 are:
Room: 3004
Instructor: Haynes
Time: 8:00 am

内容的提问来源于stack exchange,提问作者John Inf

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 04:10:30