(已关闭)赋值前引用的局部变量"退出"?



我在Wing IDE上运行python 2.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

怎么了?

您的代码运行良好,如下所示:

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")
<<p>

演示/h1>

int()

但是,如果你使用while循环,为什么不直接使用break来代替布尔值呢?它干净多了。而不是exit = True,只需键入break,循环就会结束。

如果我对你输入的内容的理解是正确的,你应该以:

结束
    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")

相关内容

  • 没有找到相关文章

最新更新