-1

I really cannot figure out how to make the code below work. I am getting this 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 would you like A to equal?\n")
        if_statement()
    elif user_choice == "2":
        print("A equals: " + user_a)
        if_statement()
if_statement()

Can anybody help me on this? I must specify that I am new to Python. Thank you in advance.

DevLounge
  • 8,313
  • 3
  • 31
  • 44
Matt
  • 482
  • 1
  • 6
  • 15

1 Answers1

2

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: " + user_a) 
        if_statement(user_a=user_a)

if_statement()

Or, what you can also 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: " + user_a)
        if_statement()

if_statement()
DevLounge
  • 8,313
  • 3
  • 31
  • 44
  • It works perfectly- thanks again – Matt Apr 19 '16 at 20:25
  • I just used print("A equals: " + user_a) and that worked fine for the second one. The first option might not be best as in my actual code there are many different variables aswell as user_a. Finally why did you use raw_input as opposed to input – Matt Apr 19 '16 at 20:34
  • if you are on python3, raw_input became input, but on python2 they both exist and do not behave de same way: http://stackoverflow.com/questions/4915361/whats-the-difference-between-raw-input-and-input-in-python3-x – DevLounge Apr 19 '16 at 20:37