为什么我的python程序没有关闭

-1 python while-loop

如果用户没有输入yes,y,no或n,我希望此代码停止循环该函数

go = True
def levelOne():
    print "You are in a room"
    print "There is a table, on the table there is a key"
    print "There is a door to the north"
    print "Use the key to open the door and escape?"
    userInput = raw_input()
    str(raw_input).lower()
    if userInput == "y" or userInput == "yes":
        print "Ok"
    elif userInput == "n" or userInput == "no":
        print "Fine, die then"
    else:
        go = False
While go == True:
    levelOne()
Run Code Online (Sandbox Code Playgroud)

现在它无限循环,为什么会这样?

aba*_*ert 5

问题是levelOne没有修改全局变量go,它正在创建一个具有相同名称的新局部变量,一旦函数返回就会消失.*

修复是添加global go到函数定义的顶部.

话虽这么说,使用全局变量几乎不是最好的解决方案.为什么不只是有功能,例如,return True或者return False,你可以写while levelOne(): pass


我们在谈论它时的一些旁注:

  • (a)学习如何使用调试器,或者(b)习惯print在每个中间步骤之后添加语句,这是一个好主意.在试图弄清楚出了什么问题时,要知道出现问题的地方比试图查看整个大画面视图并猜测可能存在错误的地方要有所帮助.
  • str(raw_input)试图调用strraw_input函数本身,这意味着它会给你类似'<built-in function raw_input>'.你想在结果上调用它raw_input.您存储在名为的变量中userInput.
  • strraw_input无论如何,结果是没用的.它保证是一个字符串,所以为什么要尝试将其转换为字符串?
  • 只是调用str一些东西,然后调用lower结果,然后忽略它返回的任何东西,都没有效果.这些函数都没有修改它的输入,它们只返回一个值,如果你想从中获得任何好处,你必须将它用作参数或存储在变量中.
  • if go == True:几乎从来没用过.如果你只是想检查那go是真的,只需使用if go:.如果你真的想确保它完全是单例常量True,而不是其他任何真相,请使用is True.(1 == True但是1 is not True,除其他原因外.)

*在Python中,无论何时指定名称,总是创建或重新绑定局部变量 - 除非您已明确告知它,否则使用global(或nonlocal)语句,在这种情况下,它会创建或重新绑定全局(或非本地)闭合)变量.