在赋值Python 3.4.5之前引用的局部变量

时间:2016-07-20 22:59:35

标签: python

我正在阅读LearnPythonTheHardWay一书,我被困在ex35上。我决定创建自己的游戏,因为他在Study Drills上问道。我有gold_room功能就像他一样,但它会在两个代码(他和我的代码)上引发标题错误。

def gold_room():

    print("You enter a room full of gold.")
    print("Do you take the gold and run to the exit or you just walk out with nothing in your hands?")

    choice = input("> ")

    if choice == "take":
        print("How much do you take?")
        choice_two = input("> ")

        if "0" in choice_two or "1" in choice_two:
            how_much = int(choice_two)
        else:
            print("Man, learn to type a number.")

        if how_much < 50:
            print("You're not greedy. You win!")
            exit(0)
        else:
            print("You greedy bastard!")
            exit(0)
    elif choice == "walk":
        print("You're not greedy. You win!")
        exit(0)
    else:
        print("I don't know what that means")
  

UnboundLocalError:局部变量&#39; how_much&#39;在分配前引用

1 个答案:

答案 0 :(得分:3)

您收到该错误是因为您在为其分配任何值之前引用变量how_much。 :)

这发生在以下行:if how_much < 50:

在代码执行的那一点,是否定义how_much取决于先前的条件(if "0" in choice_two or "1" in choice_two:)是否。{/ p>

编写的代码并没有多大意义;如果用户 输入了一个数字,那么你应该考虑how_much是多少,这是第一个条件应该确定的。

尝试这样的事情,而不是:

if "0" in choice_two or "1" in choice_two:
    how_much = int(choice_two)
    if how_much < 50:
        print("You're not greedy. You win!")
        exit(0)
    else:
        print("You greedy bastard!")
        exit(0)
else:
    print("Man, learn to type a number.")