[Tutor] Guess my number? Guess what's wrong!

Jim Byrnes jf_byrnes at comcast.net
Sat Apr 17 22:32:20 CEST 2010


Matthew Carpenter-Arevalo wrote:
> Hi Everyone,
>
> I'm a beginner python programmer, and I've been working on
> the perennial 'guess my number' example.
>
> When I run this in my module, I get an infinite loop of 'higher' or 'lower.'
> Can anyone see where I'm going wrong herE?
>
> Thanks,
>
> MCA
>
>
> # Guess my number
>
> # the computer picks a random number between 1 and 100
> # the player tries to guess it and the computer lets
> # the player know if the guess is too high, too low
> # or right on the money
>
> print "\tWelcome to 'Guess my number'!"
> print "\nI'm think of a number between 1 and 100."
> print "Try to guess it in as few attempts as possible. \n"
>
> # set the initial values
> # the number - represents the number the player has to guess
> # raw_input = the player's first guess&  converts it into an integer.
> # tries = # of guesses so far.
>
> import random
>
> the_number = random.randrange(100) + 1
> guess = int(raw_input("Take a guess: "))
> tries = 1
>
> # guessing loop
> while (guess != the_number):
>      if (guess>  the_number):
>          print "lower..."
>      else:
>          print "Higher..."
>
> guess = int(raw_input("Take a guess: "))
> tries += 1

Move the above two lines to align with "else" so they become part of the 
while loop.

> print "You guessed it! The number was", the_number
> print "and it only took you", tries, "tries!\n"
>
> raw_input("\n\nPress the enter key to exit.")
>
Regards,  Jim


More information about the Tutor mailing list