繁体   English   中英

为什么我的python程序无法关闭

[英]Why does my python program not close

如果用户未输入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()

现在它无限循环,这是为什么呢?

问题在于levelOne并没有修改全局变量go ,而是创建了一个具有相同名称的新局部变量,该局部变量在函数返回时就消失了。*

解决方法是将global go添加到函数定义的顶部。

话虽这么说,使用全局变量几乎永远不是最好的解决方案。 为什么不仅仅拥有函数,例如, return Truereturn False ,那么您可以只while levelOne(): pass编写?


我们在此注意一些注意事项:

  • (a)学习如何使用调试器,或(b)在每个中间步骤之后习惯于添加print语句,这是一个好主意。 当试图找出问题出在哪里时,知道什么地方首先出了问题比试图查看整个全局视图并猜测可能出了什么问题要有用得多。
  • str(raw_input)试图在raw_input函数本身上调用str ,这意味着它将为您提供类似于'<built-in function raw_input>' 您想在raw_input结果上调用它。 您将其存储在名为userInput的变量中。
  • 无论如何,对raw_input结果的str都是无用的。 它保证是字符串,那么为什么要尝试将其转换为字符串呢?
  • str某事调用str ,然后对结果调用lower ,然后忽略其返回的任何内容,都无效。 这些函数都不修改其输入,它们仅返回一个值,如果您想从中获得任何好处,则必须将其用作参数或存储在变量中。
  • if go == True:几乎没有用。 如果您只想检查go是否正确,请使用if go: :。 如果您真的想确保它是单身常量True ,而不是其他的true,请使用is True (除其他原因外, 1 == True ,但1 is not True 。)

*在Python中,每当您分配一个名称时,它始终会创建或重新绑定一个局部变量-除非您另行明确地告诉它,否则要使用global (或非nonlocal )语句,在这种情况下,它将创建或重新绑定一个全局(或非nonlocal )语句-local闭包)变量。

尽管有很多关于您的代码的批评,但以下内容应按您的预期工作:

 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()
     userInput = str(userInput).lower()
     if userInput in ("y", "yes"):
         print "Ok"
     elif userInput in ("n", "no"):
         print "Fine, die then"
     else:
         return False
     return True


 while levelOne():
     pass

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM