UnboundLocalError:局部变量 'password' 在赋值前被引用

0 投票
1 回答
2986 浏览
提问于 2025-04-18 08:33
def start():

    global smallq
    global medq
    global larq
    check = input("Would you like to change prices? Press Y to change or Press N to  continue to order: ")

    if check == "Y":
        password = input("What is the password?: ")
    else:
        print("Continuing to order...")
        smallq = 50
        medq = 120
        larq = 180
        order()

    if password == "please":
        quilt_price()
    else:
        print("Wrong password", "\n", "Continuing to order...")
        smallq = 50
        medq = 120
        larq = 180
        order()

异常:

Traceback (most recent call last):
  File "/Users/palerj09/Documents/SAC RW.py", line 128, in <module>
    start()
  File "/Users/palerj09/Documents/SAC RW.py", line 18, in start
    if password == "please":
UnboundLocalError: local variable 'password' referenced before assignment

如果我在输入时写“N”,程序会运行 order(),一切都正常,但一旦 order() 完成后就会出现错误。我试着把 password 设为全局变量,但似乎没有效果。有什么想法吗?

1 个回答

2

如果输入的不是 "Y" 呢?那么 password 就不会被创建,这样当你去检查 if password == "please" 时,就会出现错误。或许你可以在条件判断之前先把 password 设置为 None

撰写回答