[Tutor] Guessing a number with limited no. of tries game gone wrong.

Ros Daniel rozdaniel at hotmail.com
Tue Mar 28 19:20:18 CEST 2006

I am a newbie at Python. Just bought Python Programming 2nd ed. by Michael 
Dawson. While I understand the concepts as the book is going through the 
code, and I am able get the same results, when it comes to applying what 
I've learned to the exercises at the end of each chapter, I seem to be 
stumped. I think my logic is off somehow. I am able to get the program to 
work if it's just a case of the user guessing the random number, and then 
being told they guessed correctly in a certain number of tries. It's when 
the user has a limited number of guesses that I am stumped. Either I get an 
infinite loop, or the program will say I guessed right in a certain number 
of tries, but the guess is not correct

Can anyone explain to me what I'm missing and doing wrong? Thanks.

# Modify the Guess My Number game so that the player has a limited number of 
guesses. If the player fails to guess in time, the program should display an 
appropriately chastising message.

import random

print "Welcome to the new and improved 'Guess My Number' game."
print "This time you have a limited number of guesses, so guess wisely.\n"

the_number = random.randrange(100) + 1

guess = int(raw_input("Take a guess: "))
tries = 1

# guessing loop
while (guess != the_number):
    if tries > 5:
    elif guess > the_number:
        print "Lower..."
    elif guess < the_number:
        print "Higher..."

    guess = int(raw_input("Guess again:"))
    tries += 1

# message of congratulations
print "You guessed it! The number was", the_number
print "And it only took you", tries, "tries!\n"

More information about the Tutor mailing list