Python while loop with one condition issue

Issue

I am learning Python and was doing an exercise with the while loop statement and got confuse on why it works the way it does. For an exercise, I have to code a basic guessing game where u had three trys to guess a word. I know that in order to run the while loop statement, the condition has to be true. When I did the exercise, I had one condition expression in my while loop code and when I ran it, it didn’t work. it seems like it didn’t understand that my variable "out_of_gussess" was now true. I originally coded this:

secret_word = "giraffe"
guess = ""
guess_count = 0
guess_limit = 3
out_of_guesses = False

while guess != secret_word:
    if guess_count < guess_limit: 
        guess = input("Enter guess: ")
        guess_count += 1
    else:
         out_of_guesses = True

if out_of_guesses: 
    print("out of guesses, You lose!")

else: 
    print("You Win!")

When I ran the code, and wasn’t able to guess the word within the three attempts, my whole code breaks.

If I change the code like this below:

secret_word = "giraffe"
guess = ""
guess_count = 0
guess_limit = 3
out_of_guesses = False

while guess != secret_word and out_of_guesses != True:
     if guess_count < guess_limit: 
         guess = input("Enter guess: ")
         guess_count += 1
     else: 
         out_of_guesses = True

if out_of_guesses: 
    print("out of guesses, You lose!")

else: 
    print("You Win!")

The code rans normally without breaking and gives me an output of I lose or win depending if I guessed it or not. I am trying to understand why do I need to have my variable "out_of_gusses" to be part of the while loop condition in order for my code to work?

Solution

Your while loop in the first code snippet doesn’t have a case that checks to see if the guess limit has been reached so when you make your third guess and it is incorrect, the while loop sees that your guess is incorrect and then once inside the while loop it sets out_of_guesses to True because guess_count is no longer less than guess_limit then repeats the loop infinitely because the guess is always wrong which never allows it to move past the while loop and get to tell the user whether they were right or wrong.

Your second code snippet has that condition that checks out_of_guesses which stops the loop after it’s been set to True.

Answered By – Connor Dudley

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published