I'm taking Computer Science for GCSE and we have a project due, but I can't seem to figure out how to work functions. It tells me that "NameError: name 'option1' is not defined" and even when I define it, it doesn't seem to work. If you could check the code below and tell me how to fix things, explaining how and why it didn't work, I'd be super grateful! Thanks! ( For now please do ignore the register and leaderboard functions, I'll figure those out myself one I understand how the Login function should work. )
##### login, register or see the leaderboard.
def option():
option1 = int(input("""Would you like to:
1. Login
2. Register
3. See the Leaderboard"""))
##### MAIN CODE
while choice == True:
option()
if option1 == 1:
login()
choice = False
elif option1 == 2:
register()
choice = False
elif option1 == 3:
leaderboardopen()
choice = False
else:
print("Incorrect value given. Please try again.")
3 Answers 3
You just need to return the chosen option and capture the returned value in your main code:
##### login, register or see the leaderboard.
def option():
option1 = int(input("""Would you like to:
1. Login
2. Register
3. See the Leaderboard"""))
return option1
##### MAIN CODE
choice = True
while choice == True:
option1 = option()
if option1 == 1:
login()
choice = False
elif option1 == 2:
register()
choice = False
elif option1 == 3:
leaderboardopen()
choice = False
else:
print("Incorrect value given. Please try again.")
Comments
As Robert and Paritosh mentioned above the option1 doesn't exist outside of the option function. I can suggest the following solution:
def option():
return int(input("Would you like to:"))
##### MAIN CODE
while choice == True:
option1 = option()
if option1 == 1:
login()
# continue your logic
Comments
You haven't defined choice. Also you are declaring option1 inside a function, so when you are out of that function it is not defined. Try this, you need to return something from the function.
##### login, register or see the leaderboard.
choice = True
def option():
option = int(input("""Would you like to:
1. Login
2. Register
3. See the Leaderboard"""))
return option
##### MAIN CODE
while choice == True:
option = option()
if option == 1:
login()
choice = False
elif option == 2:
register()
choice = False
elif option == 3:
leaderboardopen()
choice = False
else:
print("Incorrect value given. Please try again.")
optionfunction's block.