[Python] Why doesn't the condition of my while loop 'apply' to my print() statement?

Discussão em 'Python' iniciado por Stack, Fevereiro 2, 2025.

  1. Stack

    Stack Membro Participativo

    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:


    1. 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?


    2. Why did it keep printing "Wrong answer!" after the correct input in the first code even after adding a break?

    Continue reading...

Compartilhe esta Página