Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Lindsey Mote
seal-mask
.a{fill-rule:evenodd;}techdegree
Lindsey Mote
Data Analysis Techdegree Student 1,148 Points

Number Guessing Game - Allowing Too Many Guesses

I'm working on the initial steps of my number guessing game. I have it limited to 5 attempts, but it is allowing unlimited attempts and I can't quite figure out why. Here is my code:

import time
import random

game_solution = random.randint(1, 20)
attempt = 5

print("Welcome to Lindsey's Guessing Game!")
time.sleep(1)

play_game = input("Would you like to play? Yes or No  ")

if play_game.lower() == "no":
    print("Have a great day!")

if play_game.lower() == "yes":
    print("Please choose a number between 1 and 20.  ")
    while attempt > 0:
        player_guess = int(input(""))

        if player_guess < game_solution:
            print("Nope, too low! Guess again:  ")

        elif player_guess > game_solution:
            print("Nope, too high! Guess again:  ")

        else:
            print("You guessed it! Nice job!")
            play_again = input("Would you like to play again?  ")

    while attempt < 5:
        print("Sorry, you are out of guesses. The answer was {}.".format(game_solution))

1 Answer

Steven Parker
Steven Parker
231,269 Points

The loop checks the value of "attempt", but it is never changed so the loop continues forever.

The last thing done in the loop should be to reduce the value of "attempt" (attempt -= 1).

Then after the loop, you will probably want a simple "if" instead of a another "while" to print out the message.