首页 > 解决方案 > Basic guessing game doesn't give any output

问题描述

I attempted to make a simple word guessing game, where the user has 3 attempts to guess a word. If the user guesses the word within 3 attempt, the program returns "Yay, you win!" If they do not guess within the 3 attempts, the program is supposed to return "Out of attempts! You lost!", however I am not getting any output when the user fails the game.

The program also tells the user how many guesses he has remaining after each incorrect guess, (except the last guess, where the output should be "Out of attempts! You lost!".

secret_word = "giraffe"
guess = ""
guesses_remaining = 3
out_of_guesses = False

while secret_word != guess:
    if guesses_remaining != 0:
        guess = input("Enter guess: ")
        guesses_remaining -= 1
        if guesses_remaining != 0:
            if secret_word != guess:
                print("You have " + str(guesses_remaining) + " guesses remaining!")
    else:
        out_of_guesses = True


if out_of_guesses == False:
    print("Yay, you win!")
else:
    print("Out of attempts! You lost!")

I can't figure out why I get no output when the user fails to guess within the three attempts.

标签: pythonpython-3.x

解决方案


Since you said that you're brand new to Python, I started out by changing your code as little as possible so you can see how you could fix what you've written to make it work.

Your problem can be fixed by adding and not out_of_guesses to your while statement condition. You could also have added a line with the keyword break after the line out_of_guesses = True. Using breakends whatever loop you are in right away.

secret_word = "giraffe"
guess = ""
guesses_remaining = 3
out_of_guesses = False

#Changing the condition of the while loop makes sure the loop doesn't continue 
#after the player is out of guesses
while secret_word != guess and not out_of_guesses:
    if guesses_remaining != 0:
        guess = input("Enter guess: ")
        guesses_remaining -= 1
        if guesses_remaining != 0:
            if secret_word != guess:
                print("You have " + str(guesses_remaining) + " guesses remaining!")
    else:
        out_of_guesses = True


if out_of_guesses == False:
    print("Yay, you win!")
else:
    print("Out of attempts! You lost!")

Example output:

Enter guess: fox
You have 2 guesses remaining!
Enter guess: bear
You have 1 guesses remaining!
Enter guess: mouse
Out of attempts! You lost!

I would like to add that your code can be simplified considerably whilst maintaining its behavior:

secret_word = "giraffe"
guesses_remaining = 3

while guesses_remaining > 0:
    guess = input("Enter guess: ")
    guesses_remaining -= 1
    if guess == secret_word:
        print("Yay, you win!")
        break
else:
    print("Out of attempts! You lost!")

推荐阅读