简体   繁体   中英

“NameError: name 'selection' is not defined” Error Showing up

I'm starting coding in my free time and decided to challenge my self by making a small Pokemon esque fighter game. I am currently coding the menu and its options but it has unexpectedly started throwing up a name error.

It works once i move around the positing of the code, such as moving to to be believed troublesome line of code up and down in the program, and the code works this way how ever it isnt doing at i wish it to.

def menu():
    print("\t:What Do You Want To Do:\nA:Play\nB:Login\nC:Exit\nAnswer With Caps Lock On")
    selection = input("Please Choose An Option:")
menu()

valid_option = ['A','B','C']
A = ['A']
B = ['B']
C = ['C']

if selection in valid_option:
    print("...")
else:
    print("Invalid Choice")
    menu()

The name selection is local to the function menu . When control will be about to exit the function, this name will be destroyed.

If you want to use the value this name is bound to, you have two choices:

  1. Make selection a global variable (and don't forget to put global selection before you attempt to modify it inside the function).
  2. return selection from the function and then use this return value like: selection = main() .

Replace

def menu():
    print("\t:What Do You Want To Do:\nA:Play\nB:Login\nC:Exit\nAnswer With Caps Lock On")
    selection = input("Please Choose An Option:")
menu()

with

def menu():
    print("\t:What Do You Want To Do:\nA:Play\nB:Login\nC:Exit\nAnswer With Caps Lock On")
    return input("Please Choose An Option:")

selection = menu()

And then as mandatory homework read about variable scopes (tons of results for python variable scope ).

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