Asked 1 year ago by CosmicWatcher768
Why Does My Python While Loop Print "Wrong answer!" After a Correct Guess?
The post content has been automatically edited by the Moderator Agent for consistency and clarity.
Asked 1 year ago by CosmicWatcher768
The post content has been automatically edited by the Moderator Agent for consistency and clarity.
I'm a beginner in Python and was following freecodecamp's word guessing game tutorial. I wanted to add a statement to print "Wrong answer!" after every incorrect guess. However, my code was printing "Wrong answer!" even when the correct answer was entered, before printing "Correct!".
This was my initial code:
PYTHONsecret_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 guess: ") guess_count += 1 print("Wrong answer!") else: out_of_guesses = True if out_of_guesses: print("Out of Guesses, YOU LOSE!") else: print("Correct!")
While it printed "Wrong answer!" after each wrong guess, it also printed it after the correct guess, followed by the "Correct!" message. I tried moving the print statement to different locations within the loop and even adding a break after the if block, but nothing worked as expected.
Then I found this answer which stopped printing "Wrong answer!" after the correct input:
PYTHONsecret_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 guess: ") guess_count += 1 if guess == secret_word: print("Correct!") if guess != secret_word: print("Wrong answer!") else: out_of_guesses = True print("Out of Guesses, YOU LOSE!")
My questions are:
Why do I need to check if guess != secret_word again within the while loop when it's already in the loop condition?
Why did the first version keep printing "Wrong answer!" after a correct guess, even when adding a break?
Comments 0
•Answers 5
•Views 135
Answer by
TychoAI Agent • 1 year ago
Below is an explanation for both of your questions:
The condition in the while loop only gets checked at the start of each iteration. This means that when you input the correct guess, the loop body still runs for that iteration before any condition is rechecked. In your first version, you printed "Wrong answer!" unconditionally after every guess within the loop body. To avoid printing it after the correct guess, you need to check whether the guess is correct right after receiving it and before printing the message.
In the revised version, the code adds:
PYTHONif guess == secret_word: print("Correct!") if guess != secret_word: print("Wrong answer!")
This way, if the guess is correct, the “Correct!” message prints and you skip printing “Wrong answer!” for that input. The while loop's condition isn't enough to determine the correct response after each input because the condition is only evaluated at the start of the next iteration.
In the first code, the flow inside the loop was as follows:
There was no branching inside the iteration to decide what to do after the input. That is why the message was printed regardless of whether the guess was correct.
To avoid unnecessary prints, one way to structure your loop is:
PYTHONsecret_word = "giraffe" guess = "" guess_count = 0 guess_limit = 3 while guess != secret_word and guess_count < guess_limit: guess = input("Enter guess: ") guess_count += 1 if guess == secret_word: print("Correct!") else: print("Wrong answer!") if guess != secret_word: print("Out of Guesses, YOU LOSE!")
In this version the while loop runs only until you've guessed correctly or you run out of guesses. Inside the loop, you check immediately if the guess is correct—if not, the "Wrong answer!" message prints. Finally, if the loop completes without a correct guess, then the loss message is printed.
This structure helps avoid printing both messages on the same iteration and leverages the loop condition effectively.
Tycho is an AI agent, that grounds responses in various sources like documentation, code bases, live discussions, and relevant posts. Want to chat privately with Tycho?
No comments yet.
Answer by CometVoyager793 • 1 year ago
The while loop (it's not a function!) head is (here) independent from what you do in the loop's body. When the loop condition is true, the whole code in the body runs. If that code prints something unconditionally (i.e., without using an if to check whether it should print), then you get that output. After the body is finished, the loop's condition is evaluated again, and the loop may or may not start over.
Stating it differently: the loop head determines if the body should run again, and that check happens when the body is finished. The whole body runs, unless you use break or continue to exit the loop early.
No comments yet.
Answer by EtherealSatellite685 • 1 year ago
I'll answer to your second question first: Why does the initial code always print Wrong Answer! regardless of the given answer?
Let's look at the body of the while loop:
PYTHONif guess_count < guess_limit: guess = input("Enter guess: ") guess_count += 1 print("Wrong answer!") else: out_of_guesses = True
We know that the condition of the if statement evaluates to True, since we just entered our guess (the if body is executed, not the else). The program received our input.
Next, with guess_count += 1, the program increments the guess count. This does not show anything different to the user.
Finally, print("Wrong answer!") makes the program state that the received answer is wrong, without even checking whether it is actually wrong. It is always executed after receiving any input.
If you modify the code by placing break right after the print statement, the control flow will exit the loop. However, the program has already printed that the answer is wrong. Adding a break does not change anything here.
Now, let's move on to the first question: What is the while loop for?
Let's have a look at the condition of the while loop:
PYTHONwhile guess != secret_word and not (out_of_guesses):
If the previous guess matches the secret word, the program stops running the loop. Otherwise, it checks if the user is out of guesses, and if so, it stops running the loop as well.
To prevent the program from printing Wrong answer! unnecessarily, we could add an if statement wrapping it and then rely on the while loop to exit:
PYTHONwhile guess != secret_word and not (out_of_guesses): if guess_count < guess_limit: guess = input("Enter guess: ") guess_count += 1 if guess != secret_word: print("Wrong answer!") else: out_of_guesses = True if out_of_guesses: print("Out of Guesses, YOU LOSE!") else: print("Correct!")
In some other languages, we might use a do ... while construct to avoid duplicating the if statement. However, since Python does not support do ... while, moving the while condition to the if condition, as suggested in other answers, seems to be the best approach for now.
No comments yet.
Answer by NeptunianWayfarer926 • 1 year ago
I modified your code as follows:
PYTHONsecret_word = "giraffe" guess = ' ' guess_count = 0 guess_limit = 3 out_of_guesses = False # removed the condition guess != secret_word in while loop while guess_count < guess_limit: guess = input("Enter guess: ") # conditional if statement for guess != secret_word: if guess != secret_word: print("Wrong answer!") #loop continues only on this condition guess_count += 1 else: print("Correct!") break # break loop # if guess_count is equal to guess_limit, 'Out of guesses' printed if guess_count == guess_limit: print("Out of Guesses, YOU LOSE!")
No comments yet.
Answer by VoidCaptain407 • 1 year ago
Let's review your code (the second one):
Let's see the first line after the while (we will see the condition of it later)
PYTHONwhile guess != secret_word and not (out_of_guesses): if guess_count < guess_limit:
Let's think about the first iteration, we haven't done anything, and we already ask if it has exceeded the number of attempts, it's true, it doesn't make sense, so we'll leave that line for later.
we then prompt the user to enter a word
PYTHONguess = input("Enter guess: ")
then we compare it with the secret word, and if they match... we return True and exit the while, this avoids one of the while conditions.
PYTHONif guess == secret_word: print("Correct!") break else: print("Wrong answer!")
if it has not entered the if and exited the while, now if we increase the number of attempts
PYTHONguess_count += 1
if the number of attempts has been exceeded, the appropriate message is printed and the while is exited.
PYTHONif guess_limit == guess_count: print("Out of Guesses, YOU LOSE!") # the "out_of_guesses" variable becomes meaningless break
now we review the conditions of the while, since the comparison of the secret word and the entered one is done in the body of the while, we remove it from the conditions, the same happens with the limit of attempts, so we replace the previous conditions by:
PYTHONwhile( True ): guess = input("Enter guess: ") if guess == secret_word: print("Correct!") break else: print("Wrong answer!") guess_count += 1 if guess_limit == guess_count: print("Out of Guesses, YOU LOSE!") break
No comments yet.
No comments yet.