python - UnboundLocalError: local variable 'user_a' referenced before assignment -
this question has answer here:
- python variable scope error 10 answers
i cannot figure out how make code below work. getting exception:
unboundlocalerror: local variable 'u' referenced before assignment
user_a = "no selection" def if_statement(): user_choice = input("pick 1 or 2\n") if user_choice == "1": user_a = input("what equal?\n") if_statement() elif user_choice == "2": print("a equals: " + user_a) if_statement() if_statement()
can me on this? must specify new python. thank in advance.
solution(s):
use default values parameters:
def if_statement(user_a='no selection'): user_choice = raw_input("pick 1 or 2\n") if user_choice == "1": u = input("what equal?\n") if_statement(user_a=u) elif user_choice == "2": print("a equals: " + user_a) if_statement(user_a=user_a) if_statement()
or, can use global
this:
user_a = "no selection" def if_statement(): global user_a # here trick ;-) user_choice = raw_input("pick 1 or 2\n") if user_choice == "1": user_a = input("what equal?\n") if_statement() elif user_choice == "2": print("a equals: " + user_a) if_statement() if_statement()
Comments
Post a Comment