[Tutor] Guess my number game

William Mhlanga reddazz at gmail.com
Thu Dec 15 20:44:48 CET 2005


I have been trying to write a guess my number game (using Michael Dawsons
book), where the computer guesses the number that I thought of. Here is my
code so far,
#The Guess My Number Game
#
#The computer picks a random number between 1 and 50
#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
#If the player fails to guess the number after 5 tries
#the game ends and the computer prints a chastising message
#

print "\t\t\tWelcome to \"Guess My Number\"!"
import random

print "\nThink of a number between 1 and 50."
print "I will try to guess it in as few attempts as possible.\n"

number = input ("Enter the number: ")

#the computer guesses the number using the random function
guess = random.randrange (50) + 1
tries = 1

#FIXME
while (guess != number):
        if (guess > number):
                print "You chose", guess, "the number is Lower ..."
        else:
                print "You chose", guess, "the number is Higher ..."
        guess = random.randrange (50) + 1
        tries += 1

print "You guessed it! The number was", number
print "And it only took you", tries, "tries!\n"

raw_input ("Press <ENTER> to exit.")

The program works ok, but the computer sometimes repeats the same numbers
when asked to guess. How can I rewrite it so that it guesses like what a
human being does i.e. if the number is less than 20, you do not guess
numbers above 20.

Thanks for your help.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20051215/4f2082eb/attachment.htm


More information about the Tutor mailing list