从函数调用时,简单代码会中断

2024-09-30 14:21:13 发布

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

我有以下代码:

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语句中,它就可以工作了。有人知道为什么吗


Tags: the代码youinputsecretdefve语句
3条回答

在函数askForGuess()的作用域中为guess赋值并不会改变全局变量guess的值,这就是为什么您永远无法退出循环的原因

正如abe所说,这是因为在这两个作用域中有两个称为guess的变量

由于globals的使用被认为是不好的代码,我的实现是:

secret_word = "secretword"
guess = ""

def askForGuess():
    guess = input("Introduce the secret word :")
    print(guess,secret_word)
    return guess

while guess != secret_word:
    guess = askForGuess()
    

 
print("You've won!")

这里基本上发生的是循环中的guess是一个新变量,而不是while循环检查的变量。这是因为第2行中的guess变量未声明为全局变量。下面的代码应该可以工作

secret_word = "secretword"
global guess
guess = ""


def askForGuess():
    global guess
    guess = input("Introduce the secret word :")
    print(guess, secret_word)


while guess != secret_word:
    askForGuess()

print("You've won!")

希望以上内容对您有所帮助,对于解释得很好的问题,您做得很好

相关问题 更多 >