Home > Net >  Understanding a component in python guessing game code
Understanding a component in python guessing game code

Time:05-12

I am new to Python and using some online resources to learn stuff. I am trying to wrap my head around a guessing game, but I am getting confused by one condition in the code.

secret_word = "giraffe"
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

if out_of_guesses:
     print("You Lose!")
else:
     print("You Win!")

I ma able to follow the code, but get lost at not(out_of_guesses) condition in the while loop. Can someone explain this part?

From what I understand, it says that when the secret_word is not equal to the guess and out_of_guess is true, keep looping, else break out of the loop. I am probably wrong. Can someone please help me understand this.

CodePudding user response:

Split into two parts, you have:

guess != secret_word

This means quess does not equal secret_word

clearly

And

not(out_of_guesses)

not out_of_guesses is checking that variable is False

Where not flips the bool into the opposite.

Example:

>>> x = False
>>> x
False
>>> not x
True

The and means both conditions must be True for the while loop to run


Edit

You will leave the while loop when at least one condition is False.


The first condition will be False when guess = input("Enter a guess: ") is the secret_word

The second condition will be False when out_of_guesses = True (that line runs). Which will run when guess_count < guess_limit

CodePudding user response:

Your while loop means: while guess not equal to secret_word and not out_of_guesses - which means your out_of_guesses must be false => so that not(out_of_guesses) can be True; then the loop keeps running, otherwise, breaking out of the loop.

  • Related