简体   繁体   中英

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 . Wouldn't or fit better here?

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. and means that both conditions have to be true for the expression to be true. So if either of the conditions is false, the and expression is false, and the loop stops.

If you change it to or , the expression is true if either condition is true. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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