我在一些帮助下建立了一个猜谜游戏。如果使用and
,当只有一个条件为false时,while循环为什么会终止? or
在这里适合吗?
secret_word = "pirate"
guess = ""
guess_count = 0
guess_limit = 3
out_of_guesses = False
while guess != secret_word and not(out_of_guesses):
if guess_count < guess_limit:
guess = input("Enter a guess:" )
guess_count += 1
else:
out_of_guesses = True
print("Out of guesses")
这是如何工作的?
while guess != secret_word and not(out_of_guesses):
答案 0 :(得分:1)
while
中的表达式指定循环应何时继续运行。 and
表示两个条件都必须为真,表达式才能为真。因此,如果任一条件为假,则and
表达式为假,并且循环停止。
如果将其更改为or
,则当任一条件为true时,表达式为true。因此,只要用户猜不到单词,即使他们用完了猜测,您也将继续循环播放。
答案 1 :(得分:0)
我们可以使用一些变量来描述条件:
B
现在的措辞应该更清楚地说明为什么循环应该继续以及为什么guessed_wrong = guess != secret_word
has_more_guesses = not out_of_guesses
while guessed_wrong and has_more_guesses:
# ...
guessed_wrong = guess != secret_word
has_more_guesses = not out_of_guesses
在这里使用不正确。