如何在 python 中正确使用 "while not" 循环?
How to properly use "while not" loops in python?
我从几天前开始学习 python。我确实理解 while 和 for 循环的一般概念。然而,此刻我正试图理解为刽子手游戏编写的代码,我无意中发现了以下代码行:
import random
from words import word_list
def get_word():
word = random.choice(word_list)
return word.upper()
def play(word):
word_completion = "_" * len(word)
guessed = False
guessed_letters = []
guessed_words = []
tries = 6
print("Let's play Hangman!")
print(display_hangman(tries))
print(word_completion)
print("\n")
while not guessed and tries > 0:
有一个名为“guessed”的变量最初设置为 False。
在while循环的开头写着:
while not guessed ...
但这不是双重否定吗?当 guessed = False 时,不应该 not guessed == True? 这样我们也可以只写 while True 甚至不需要变量 guessed?
或者我如何理解一般的 while not 概念?
如有任何提示,我们将不胜感激。
对 while not guessed
的最佳解释是,它本质上是在说“虽然猜测不等于真实”。这就是说它基本上是“虽然猜测是错误的”。所以 while 循环将 运行 只要猜测为假并尝试 > 0。但是,如果猜测每次都为真,则 while 循环将停止 运行ning.
关键是在这个意义上,not 并不意味着否定。这只是意味着 while 循环 运行s 只要 guessed 的值为 false 而不是 true。我理解其中的困惑,但这是一个重要的事实。
But isn't this like a double negation? When guessed = False
, then shouldn't not guessed == True
?
是的。
so that we could also just write while True
and wouldn't even need the variable guessed
?
不,因为变量 guessed
的值可以(并且很可能会)在循环执行期间的某个时刻变为 True
—— 毕竟,变量称为变量因为它的值可以在不同的程序执行状态之间变化。然后 not guessed
将计算为 False
,并且 while
循环将终止。
另一方面,while True
循环会无限地 运行 因为 True
将始终保持 True
.
这就是 while
构造的全部要点:使用一个变量(或涉及不同值的一些更复杂的条件,例如 not variable
),该变量最初计算为 True
并使循环 运行,但当满足某些条件时会将其值更改为 False
,从而导致循环终止。
我从几天前开始学习 python。我确实理解 while 和 for 循环的一般概念。然而,此刻我正试图理解为刽子手游戏编写的代码,我无意中发现了以下代码行:
import random
from words import word_list
def get_word():
word = random.choice(word_list)
return word.upper()
def play(word):
word_completion = "_" * len(word)
guessed = False
guessed_letters = []
guessed_words = []
tries = 6
print("Let's play Hangman!")
print(display_hangman(tries))
print(word_completion)
print("\n")
while not guessed and tries > 0:
有一个名为“guessed”的变量最初设置为 False。
在while循环的开头写着:
while not guessed ...
但这不是双重否定吗?当 guessed = False 时,不应该 not guessed == True? 这样我们也可以只写 while True 甚至不需要变量 guessed?
或者我如何理解一般的 while not 概念?
如有任何提示,我们将不胜感激。
对 while not guessed
的最佳解释是,它本质上是在说“虽然猜测不等于真实”。这就是说它基本上是“虽然猜测是错误的”。所以 while 循环将 运行 只要猜测为假并尝试 > 0。但是,如果猜测每次都为真,则 while 循环将停止 运行ning.
关键是在这个意义上,not 并不意味着否定。这只是意味着 while 循环 运行s 只要 guessed 的值为 false 而不是 true。我理解其中的困惑,但这是一个重要的事实。
But isn't this like a double negation? When
guessed = False
, then shouldn'tnot guessed == True
?
是的。
so that we could also just write
while True
and wouldn't even need the variableguessed
?
不,因为变量 guessed
的值可以(并且很可能会)在循环执行期间的某个时刻变为 True
—— 毕竟,变量称为变量因为它的值可以在不同的程序执行状态之间变化。然后 not guessed
将计算为 False
,并且 while
循环将终止。
另一方面,while True
循环会无限地 运行 因为 True
将始终保持 True
.
这就是 while
构造的全部要点:使用一个变量(或涉及不同值的一些更复杂的条件,例如 not variable
),该变量最初计算为 True
并使循环 运行,但当满足某些条件时会将其值更改为 False
,从而导致循环终止。