(关闭)赋值前引用的局部变量“exit”?

2024-04-25 07:55:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在Wing IDE上运行python2.75

代码:

exit = False

while not exit:

    selection = int(raw_input("Press 1 to go and 0 to quit: ")
    if selection == 1:
       print("yay")
    elif selection == 0:
       print("Goodbye")
       exit = True
    else:
       print("Go away")

当我按0时,它说:

local variable 'exit' referenced before assignment

怎么了?你知道吗


Tags: to代码falsegoinputrawexitnot
2条回答

您的代码工作正常,如下所示:

exit = False

while not exit:
    selection = int(raw_input("Press 1 to go and 0 to quit: "))       #added ) to correct syntax error
    if selection == 1:
        print("yay")
    elif selection == 0:
        print("Goodbye")
        exit = True
    else:
        print("Go away")

DEMO

你的int()缺少一个很接近的paren

不过,如果您使用的是while循环,为什么不简单地使用break而不是boolean呢?它干净多了。只需键入break,循环就结束了,而不是exit=True。你知道吗

如果我对您键入内容的理解是正确的,您希望最后得到:

    while True:
      selection = int(raw_input("Press 1 to go and 0 to quit: "))
      if selection == 1:
        print("yay")
      elif selection == 0:
        print("Goodbye")
        break
      else:
        print("Go away")

相关问题 更多 >