为什么“和”在while循环中起作用而“或”不起作用?

时间:2020-11-03 01:43:31

标签: python function loops while-loop

我在一些帮助下建立了一个猜谜游戏。如果使用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):

2 个答案:

答案 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 在这里使用不正确。