尝试从字典中获取3种信息,不会通过(不是全局的)

2024-03-29 05:01:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试制作代码,从课程编号的输入中检索课程、讲师和时间(CS101)

在你输入正确的课程号后,它会告诉你房间号、教员和上课时间。你知道吗

这就是我目前所拥有的。你知道吗

def main():
    courses, instructors, times = create_info()

    print('Please enter a course number...')
    choice = input(': ').upper()

    if choice == 'CS101':
        courses.get(CS101)
        instructors.get(CS101)
        times.get(CS101)
    elif choice == 'CS102':
        print()
    elif choice == 'CS103':
        print()
    elif choice == 'NT110':
        print()
    elif choice == 'CM241':
        print()
    else:
        print('Sorry, invalid course number')
        print()
        main()

    print()
    main()



def create_info():
    courses = {'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 a.m.', 'CS102':'9:00 a.m.', 'CS103':'10:00 a.m.',
             'NT110':'11:00 a.m.', 'CM241':'1:00 p.m.'}

    return courses, instructors, times

main()

它给出了以下内容:

NameError:未定义全局名称“CS101”


Tags: getmain时间课程printtimeschoiceelif
2条回答

问题在于这些线路:

    courses.get(CS101)
    instructors.get(CS101)
    times.get(CS101)

CS101被假定为变量,而不是字符串或字典键。你知道吗

应该是这样的:

print(courses.get('CS101'))

或者

print(courses['CS101'])

如果一个字符串是单引号,那么它就需要被双引号括起来。你知道吗

使用字典的一个好处是,可以使用in操作符快速检查字典中是否有键。因此,可以用以下内容替换大的if/elif/else块:

if choice in courses:
    # do the output with choice as a key to the dictionaries
    print("Course Number:", courses[choice])
    print("Instructor:", instructors[choice])
    print("Times:", times[choice])
else: 
    # choice is not a valid key to the dictionaries
    print("Sorry, invalid course number")

这种编码方式在Python世界中被称为“三思而后行”(LBYL),因为在执行操作之前要检查要执行的操作(在字典中查找所选的类)是否有效。另一种样式(稍微高级一点)称为“请求宽恕比请求许可更容易”(EAFP),在EAFP中使用tryexcept子句来处理在某些异常情况下生成的异常。以下是如何以EAFP样式执行上述代码:

try:
    # try do the output unconditionally
    print("Course Number:", courses[choice])
    print("Instructor:", instructors[choice])
    print("Times:", times[choice])
except KeyError:
    # a KeyError is raised if choice isn't in the dictionaries
    print("Sorry, invalid course number")

在这种情况下,这两种方法没有太大区别,但在某些情况下(如果检查情况是否有效需要大量时间),EAFP可能会更快,因为可能失败的操作已经在检查无效的情况(因此它可以引发适当的异常)。你知道吗

相关问题 更多 >