简体   繁体   中英

Global name not defined Python 3

For some reason when I tap c, it gives me 'courses' is not defined.

Please enter a menu choice... [c]ourses, [i]nstructors, [t]imes: c Traceback (most recent call last):

line 15, in main print(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()

courses is a local variable in create_info so it is not visible from main .Perhaps you were meaning to use courseInfo there.

Also, you are trying to pass a parameter to create_info, when it is defined to take no parameters

You could make create_info return a dict like this

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

Change main() like so:

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)                             # <<<

I've changed the two lines marked with # <<< .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM