关于python:UnboundLocalError:在赋值之前引用的局部变量’user_a’

UnboundLocalError: local variable 'user_a' referenced before assignment

本问题已经有最佳答案,请猛点这里访问。

我真的不知道如何使下面的代码工作。我得到这个例外:

UnboundLocalError: local variable 'u' referenced before assignment

1
2
3
4
5
6
7
8
9
10
11
12
user_a ="No selection"
def if_statement():
    user_choice = input("Pick 1 or 2
"
)
    if user_choice =="1":
        user_a = input("What would you like A to equal?
"
)
        if_statement()
    elif user_choice =="2":
        print("A equals:" + user_a)
        if_statement()
if_statement()

有人能帮我吗?我必须指定我是Python的新手。提前谢谢。


解决方案(S):

使用一些默认值作为参数:

1
2
3
4
5
6
7
8
9
10
11
12
def if_statement(user_a='no selection'):
    user_choice = raw_input("Pick 1 or 2
"
)
    if user_choice =="1":
        u = input("What would you like A to equal?
"
)
        if_statement(user_a=u)
    elif user_choice =="2":
        print("A equals:" + user_a)
        if_statement(user_a=user_a)

if_statement()

或者,您也可以这样使用global

1
2
3
4
5
6
7
8
9
10
11
12
13
14
user_a ="No selection"
def if_statement():
    global user_a # here is the trick ;-)
    user_choice = raw_input("Pick 1 or 2
"
)
    if user_choice =="1":
        user_a = input("What would you like A to equal?
"
)
        if_statement()
    elif user_choice =="2":
        print("A equals:" + user_a)
        if_statement()

if_statement()