UnboundLocalError:赋值前引用的局部变量'number'

时间:2018-05-21 18:30:12

标签: python python-3.x

def straight():
    print("You went straight ahead")
    print("You run into a locked door. You try to break down the door but it 
    doesn't work..")
    print("Then you see the writing on the wall next to the door..")
    print("Call a number and then we call it even!")

    try:
        number = int(input("--> "))
    except:
        print("Not a number!")
        straight()

    if number % 2 == 0:
        print(f"You cracked the code! Your even number {number} gave you access 
        to this door")
        print("The door opens..")
        final_room()
    elif number % 2 >= 1:
        dead(f"The wrong number ({number}) caused the tunnel to collapse!")
    else:
        print("test else?")
        straight()

我对编程很陌生,所以我希望有人可以用“常规”语言帮助我哈哈!

我在这个论坛和其他网站上看过类似的问题,但我仍然无法弄清楚我做错了什么。这是我得到错误消息的功能。我的其余代码工作正常。

我不断收到以下消息: UnboundLocalError:赋值前引用的局部变量'number'

但变量已在我的函数中设置,所以我认为它会起作用。当我给出错误的输入(在这种情况下是一个字符串)时它也会起作用。当我第一次给出一个字符串时,它不起作用:hkjadhjkas

然后这个脚本会再次问我,因为它会再次运行。如果我之后输入数字20就会出现此错误。但是,在我第一次尝试给予20时,它将起作用。所以这个错误不会一直出现。

那么我做得对不对?提前谢谢你帮助我。

1 个答案:

答案 0 :(得分:1)

您的问题是,在except块中递归后,您继续运行原始函数,就像未发生异常一样,但原始函数未能设置number

即,这段代码:

try:
    number = int(input("--> "))  # Oh no, not a number
except:
    print("Not a number!")  # Jumps here
    straight()              # Runs straight
# Keeps going!!!

if number % 2 == 0:  # number never assigned!!!

尝试解析并分配给number,打印错误,递归调用straight,然后当完成时,它继续,好像没有发生错误,导致if number % 2 == 0:阅读number,但未设置它。

如果目标是使用递归调用的结果,只需更改代码:

try:
    number = int(input("--> "))
except:
    print("Not a number!")
    straight()

为:

try:
    number = int(input("--> "))
except:
    print("Not a number!")
    return straight()  # <-- Makes you return the result from the recursive call

在递归调用straight的其他地方需要进行类似的更改。

我还建议将except限制为比#34更具体的内容;所有可能的例外情况&#34 ;;你会忽略用户按Ctrl-C,系统内存不足等等。我建议使用except ValueError:这是int()本身唯一的例外情况。在解析字符串时加注,而不是盲目地捕获所有错误并假设它是无效输入。