2

出于某种原因,当我点击 c 时,它给我的“课程”没有定义。

请输入菜单选项... [c]ourses、[i]nstructors、[t]times:c Traceback(最近一次通话最后一次):

第 15 行,在主打印中(create_info(courses)) NameError: global name 'courses' is not defined

def main():
    courseInfo = create_info()

    print('Please enter a menu choice...')
    choice = input('[c]ourses, [i]nstructors, [t]imes: ').upper()

    if choice == 'C':
        print(create_info(courses))


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()
4

2 回答 2

5

courses是一个局部变量,create_info因此从main.Performance 中看不到它。也许您打算在courseInfo那里使用它。

此外,您正在尝试将参数传递给 create_info,当它被定义为不带参数时

你可以让 create_info 返回一个像这样的字典

def main():
    courseInfo = create_info()

    print('Please enter a menu choice...')
    choice = input('[c]ourses, [i]nstructors, [t]imes: ').upper()

    if choice == 'C':
        print(courseInfo["courses"])


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 dict(courses=courses, instructors=instructors, times=times)

main()
于 2012-12-18T23:51:14.083 回答
3

main()像这样改变:

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

    print('Please enter a menu choice...')
    choice = input('[c]ourses, [i]nstructors, [t]imes: ').upper()

    if choice == 'C':
        print(courses)                             # <<<

我已经更改了标有 的两行# <<<

于 2012-12-18T23:51:16.057 回答