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

Victor Bouffier victor at grupocdm.com
Wed Mar 29 02:03:20 CEST 2006


Hi Ros,

Look what happens when the user tried for more than 5 times:

    if tries > 5:
        break

This just takes you out of the loop, but it does not handle the issue
that the user did not guess correctly. The next statement will be to
print the congratulations message.

You should instead tell the user they did not make it and exit the
program altogether, probably letting them know what the actual number
was. Something like:

    if tries > 5:
        print "Too bad. You tried one too many times." 
        print "The number was", the_number
        sys.exit()

You have to 'import sys' first though.
Try it out and analyze the flow of the program. Use the debugger to try
your code one step at a time to see what is going wrong.

I would also change the initial guess to specify the range, like:

guess = int(raw_input("Take a guess between 1 and 100: "))

Best of luck.
Victor


On Tue, 2006-03-28 at 12:20 -0500, Ros Daniel wrote:
> 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:
>         break
>     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"
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 



More information about the Tutor mailing list