[Tutor] Number guessing game

Christopher Hatherly Christopher.Hatherly at anu.edu.au
Tue Oct 3 06:12:28 CEST 2006


Hi, 
I'm brand new to Python, and almost brand new to programming. I'm
teaching myself slowly through a 'Python Programming for the Absolute
Beginner' book, which is great so far. One of the challenge problems
though, was to write a script for a number guessing game, where you pick
a number and the computer tries to guess. It took me a couple of days to
get this working, and some of it is pretty messy. In particular, the
'Guess = ...' line, and the 
responses[] list' that I used. I'm happy that this works, but would like
to know how to do it better! If anyone could suggest any improvements,
that'd be great! 

Cheers
Chris

 
print """
                Welcome to the 'guess the Number' game!!!
Your job is to pick a number and my job is to try and figure it out."
        After each guess, tell me if I'm too high or too low."
          I've only got 7 goes to guess the number though ..."
"""
 
raw_input("\nPress enter when you're ready.")
 
guess = 50
responses = [guess, 0]
guess_number = 0
number = int(raw_input("\nPick a number between 1 and 100: "))
print "\nOK, guess number", guess_number +1, "is", guess
 
while (guess != number) and guess_number < 6:
    high_low = raw_input("\nToo High or too Low (H/L)? ")
 
    if high_low == "H":
        print "Darn, too high!"
        guess =
responses[guess_number]-(round(abs(responses[guess_number]-responses[gue
ss_number-1])/2))
        print "I have", 5 - guess_number, "guesses remaining."
        guess_number += 1
        responses = responses[:guess_number] + [guess]
        raw_input ("\nPress enter to continue.")
        print "\nOK, guess number", guess_number +1, "is", int(guess)
 
    elif high_low == "L":
        print "Darn, too low!"
        guess =
responses[guess_number]+(round(abs(responses[guess_number]-responses[gue
ss_number-1])/2))
        print "I have", 5 - guess_number, "guesses remaining."
        guess_number += 1
        responses = responses[:guess_number] + [guess]
        raw_input ("\nPress enter to continue.")
        print "\nOK, guess number", guess_number +1, "is", int(guess)
 
    else:
        print "Sorry, I didn't understand that."
 
if guess == number:
    print "\nHoorah!!! I got the number!!!"
    print "The number was ", number 
    print "and I only took", guess_number + 1, "guesses."
else:
    how_close = abs(guess - number)
    print "\nToo bad. The number was", number
    print "I was", int(how_close), "off getting it right."

raw_input("\n\nPress the enter key to exit.\n")



More information about the Tutor mailing list