【发布时间】:2020-10-28 14:48:19
【问题描述】:
所以我正在尝试编写一个程序,让用户输入课程编号,然后获取该课程的房间、讲师和会议时间信息。如果用户输入的课程未找到/无效,我希望能够打印终止消息,但是当我尝试时,它会出现 KeyError。 我尝试过使用 try/except 语句,但是当我执行代码时会出现 TypeError。
room_dict = {
"CS101": {
"Room": "3004"
},
"CS102": {
"Room": "4501"
},
"CS103": {
"Room": "6755"
},
"NT110": {
"Room": "1244"
},
"CM241": {
"Room": "1411"
},
}
instructor_dict = {
"CS101": {
"Instructor": "Haynes"
},
"CS102": {
"Instructor": "Alvarado"
},
"CS103": {
"Instructor": "Rich"
},
"NT110": {
"Instructor": "Burkes"
},
"CM241": {
"Instructor": "Lee"
},
}
time_dict = {
"CS101": {
"Time": "8:00 a.m."
},
"CS102": {
"Time": "9:00 a.m."
},
"CS103": {
"Time": "10:00 a.m."
},
"NT110": {
"Time": "11:00 a.m."
},
"CM241": {
"Time": "1:00 p.m."
},
}
courses = {"CS101", "CS102", "CS103", "NT110", "CM241"}
dicts = {'Room':room_dict,'Instructor':instructor_dict,'Time': time_dict}
dash_count = 50
dashes = dash_count * "-"
print(f'College Course Locater Program')
print(f'Enter a course number below to get information')
get_course = input(f'Enter a course number: ')
print(dashes)
course_num = get_course
room = room_dict[get_course]
instructor = instructor_dict[get_course]
time = time_dict[get_course]
if course_num in courses:
print(f'The details for course {get_course} are: ')
print(f"Room: {room['Room']}")
print(f"Time: {time['Time']}")
print(f"Instructor: {instructor['Instructor']}")
其他: print(course_num, '是一个无效的课程编号。')
基本上,我得到的输出是:
College Course Locater Program
Enter a course number below to get information
Enter a course number: CS # where CS is an invalid course number
--------------------------------------------------
Traceback (most recent call last):
File "C:\Users\Python\Downloads\courseinfo.py", line 75, in <module>
room = room_dict[get_course]
KeyError: 'CS'
我正在寻找的是:
College Course Locater Program
Enter a course number below to get information
Enter a course number: CS
--------------------------------------------------
(course number) is an invalid course number. # where (course number) is an invalid course number
【问题讨论】:
标签: python dictionary input keyerror