简体   繁体   English

为什么“and”在这个while循环中起作用而“or”不起作用?

[英]Why does the 'and' work in this while loop and 'or' doesn't?

I built a guessing game with some help.我在一些帮助下建立了一个猜谜游戏。 Why does the while loop terminate when only one condition is false if it's using and .如果 while 循环在使用and时只有一个条件为假,为什么它会终止。 Wouldn't or fit better here?会不会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")

How does this work?这是如何运作的?

while guess != secret_word and not(out_of_guesses):

The expression in while specifies when the loop should keep running. while的表达式指定循环应何时继续运行。 and means that both conditions have to be true for the expression to be true. and意味着两个条件都必须为真,表达式才能为真。 So if either of the conditions is false, the and expression is false, and the loop stops.因此,如果其中一个条件为假,则and表达式为假,循环停止。

If you change it to or , the expression is true if either condition is true.如果将其更改为or ,则在任一条件为真时表达式为真。 So you'll keep looping as long as the user doesn't guess the word, even if they've run out of guesses.所以只要用户没有猜出这个词,你就会一直循环下去,即使他们猜不透了。

We can use some variables to help describe the conditions:我们可以使用一些变量来帮助描述条件:

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

Now the wording should make it more clear why the loop should continue and why or is incorrect to use here.现在措辞应该更清楚为什么循环应该继续以及为什么在这里使用or使用不正确。

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

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