Matt Matt - 7 months ago 17
Python Question

Unbound Local Error in If Statement

I understand that there are lots of other questions about Unbound Local Errors but I have looked through them and could not find the answer to my issue. I can understand why this does not work but cannot really explain it. What I am looking for is both an easy to understand explanation and more importantly a way to make this work. Any other suggestions on how to improve my code would also be greatly appreciated as I am fairly new to python. Thanks in advance- an simple example of my code can be found below.

user_a = "No selection"
def if_statement():
user_choice = input("Pick 1 or 2\n")
if user_choice == "1":
user_a = input("What would you like A to equal?\n")
if_statement()
elif user_choice == "2":
print("A equals: " + user_a)
if_statement()
if_statement()


EDIT: I already looked through the question marked as a possible duplicate and could not find an answer to my particular problem.

Answer

Solution(s):

Use some default values as parameters:

def if_statement(user_a='no selection'):
    user_choice = raw_input("Pick 1 or 2\n")
    if user_choice == "1":
        u = input("What would you like A to equal?\n")
        if_statement(user_a=u)
    elif user_choice == "2":
        print("A equals: {}".format(user_a))
        if_statement(user_a=user_a)

if_statement()

Or, but I prefer the first solution, you can do is to use global like this:

user_a = "No selection"
def if_statement():
    global user_a # here is the trick ;-)
    user_choice = raw_input("Pick 1 or 2\n")
    if user_choice == "1":
        user_a = input("What would you like A to equal?\n")
        if_statement()
    elif user_choice == "2":
        print("A equals: {}".format(user_a)) # was raising an error
        if_statement()
if_statement()