我有以下代码:
secret_word = "secretword"
guess = ""
def askForGuess():
guess = input("Introduce the secret word :")
print(guess,secret_word)
while guess != secret_word:
askForGuess()
print("You've won!")
如果我在while语句中调用askForGuess(),它将永远不会打印“You'vewind!”即使我正确地介绍了这个秘密。 但是,如果我只是简单地将askForGuess()代码粘贴到while语句中,它就可以工作了。有人知道为什么吗
在函数
askForGuess()
的作用域中为guess
赋值并不会改变全局变量guess
的值,这就是为什么您永远无法退出循环的原因正如abe所说,这是因为在这两个作用域中有两个称为
guess
的变量由于globals的使用被认为是不好的代码,我的实现是:
这里基本上发生的是循环中的
guess
是一个新变量,而不是while循环检查的变量。这是因为第2行中的guess变量未声明为全局变量。下面的代码应该可以工作希望以上内容对您有所帮助,对于解释得很好的问题,您做得很好
相关问题 更多 >
编程相关推荐