简体   繁体   English

为什么我的简单程序永远不会退出while循环?

[英]Why does my simple program never exit my while loop?

It's a simple number guessing game, and the code is as follows: 这是一个简单的猜数字游戏,代码如下:

from random import randint

number = randint(0,20)
playerGuess = '0'
def guess():
    playerGuess = input("Guess a number:  ")

    if int(playerGuess) == number:
        print("Correct!")

    elif int(playerGuess) > number:
        print("Lower!")

    elif int(playerGuess) < number:
        print("Higher!")

    else:
        print("Please input a whole number.")

while int(playerGuess) != number:
    guess()

print("------------------------------------")
print("Good job!") 

I do not understand why the code does not break out of the while loop as expected. 我不明白为什么代码没有按预期退出while循环。

guess doesn't change the global value of playerGuess = '0' To do that you need to specify with the global , although there are better ways to refactor your code: guess并不会改变playerGuess = '0'的全局值。您可以使用global来指定,尽管有更好的方法来重构代码:

from random import randint

number = randint(0,20)
playerGuess = '0'
def guess():
    global playerGuess #Emphasis on this line.
    playerGuess = input("Guess a number:  ")

    if int(playerGuess) == number:
        print("Correct!")

    elif int(playerGuess) > number:
        print("Lower!")

    elif int(playerGuess) < number:
        print("Higher!")

    else:
        print("Please input a whole number.")

while int(playerGuess) != number:
    guess()

print("------------------------------------")
print("Good job!") 

Because playerGuess in guess() function is not the same variable as playerGuess of the top of file. 因为playerGuessguess()函数是不相同的变量作为playerGuess文件的顶部。 Use global playerGuess in guess() function. guess()函数中使用global playerGuess

from random import randint

number = randint(0,20)
playerGuess = '0'
def guess():
    global playerGuess
    ...

Tips&tricks: Global variables are bad, try to rewrite your code without globals. 提示:全局变量不好,请尝试在不使用全局变量的情况下重写代码。

Variables only exist in their 'namespace', which is the part of the code different variables are recognized. 变量仅存在于其“命名空间”中,这是识别不同变量的代码的一部分。 A new namespace is made for each function you write. 为您编写的每个函数创建一个新的名称空间。 This is helpful because as your projects grow, you may want to reuse common variables names for several different things. 这很有用,因为随着项目的增长,您可能希望将公用变量名称重用于几种不同的事物。

In your code, there are two different variables named playerGuess . 在您的代码中,有两个不同的变量,名为playerGuess One in the first namespace, and one in the namespace that you made for your function guess() . 在第一个命名空间中,一个在为函数guess()的命名空间中。 If we make the code like this: 如果我们这样编写代码:

while int(playerGuess) != number:
    print(playerGuess, number)           # The added line
    guess()

It becomes more clear. 它变得更加清晰。 This is a game I played with the added line: 这是我玩的带有以下内容的游戏:

0 14
Guess a number:
>>> 10
0 14     # playerGuess is still 0, not 10
Higher!
Guess a number:  
>>> 14
0 14     # I've been told I won because that happens in the guess() function
Correct!
Guess a number:  # But the while: loop doesn't know I've won
. . .

The namespace in your script outside of any functions, like where number = randint(0,20) is, is the 'global' namespace, which means values can be pulled from here from any other namespace. 脚本中任何功能之外的名称空间(例如number = randint(0,20)所在的位置number = randint(0,20)都是“全局”名称空间,这意味着可以从此处从任何其他名称空间提取值。 This is why number can be used by the guess() function- guess() checks to see if there is a variable number defined in its namespace, sees there is not, and then checks the global namespace. 这就是为什么number可以由guess()函数使用的原因guess()检查以查看是否在其命名空间中定义了一个可变number ,看是否没有,然后检查全局命名空间。 It is possible to change the global namespace from other parts of the code, but this is considered bad practice because it can be not obvious where these changes come from. 可以从代码的其他部分更改全局名称空间,但这被认为是不好的做法,因为这些更改的来源并不明显。 If you wanted to take this approach though, you could alter your code like this: 如果您想采用这种方法,则可以这样更改代码:

from random import randint

number = randint(0,20)
playerGuess = '0'
def guess():
    global playerGuess                  # The added line
    playerGuess = input("Guess a number:  ")
. . .

And now it works because guess() has been given explicit permission to alter the global namespace. 现在它可以工作了,因为对guess()给予了明确的更改全局名称空间的权限。 An alternative is to pass only the value we care about back and forth between the namespaces. 一种替代方法是仅在命名空间之间来回传递我们关心的值。

from random import randint
number = randint(0,20)
playerGuess = '0'
def guess():
    playerGuess = input("Guess a number:  ")

    if int(playerGuess) == number:
        print("Correct!")

    elif int(playerGuess) > number:
        print("Lower!")

    elif int(playerGuess) < number:
        print("Higher!")

    else:
        print("Please input a whole number.")

    return playerGuess                     # Added line

while int(playerGuess) != number:
    print(playerGuess, number)
    playerGuess = guess() # Added line, update the playerGuess in this namespace

This is considered better because now it is obvious exactly where and what alters the variable playerGuess. 之所以认为这是更好的方法,是因为现在可以很清楚地看到更改变量playerGuess的位置和原因。

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

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