Only started learning Python a few days ago. I followed freecodecamp's while loop word guessing game tutorial and wanted to add the statement, "Wrong answer!" after every wrong guess.
This was what I initially wrote:
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 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 did print after every wrong answer, it ALSO printed after the correct input, which was then followed by the "Correct!" statement.
Initially I tried moving print("Wrong answer!") to other lines within the while function and tried adding a break after the if function but nothing seemed to work.
It was only when I found this answer where "Wrong answer!" stopped printing after the correct input:
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 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!")
So my questions are:
Why do I need to define if guess != secret_word: AGAIN if I already had while guess != secret_word and not (out_of_guesses): in the while loop function?
Why did it keep printing "Wrong answer!" after the correct input in the first code even after adding a break?
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.