[Tutor] random number generator

Jim Hutchinson jim at ubuntu-rocks.org
Fri Oct 5 01:07:35 CEST 2007


I am writing a little program to test a theory and as part of teaching
myself Python. I've only been at this about a week now. I have a
program that "should" work but doesn't. It generates a random number
between 1 and 2 out to 10 decimal places. I think there is something
wrong with how my random number is generated or defined or how my
guesses are defined. I added a line to tell me what the random number
is and then if I enter it as a guess it doesn't match and exit the
loop. Any idea what I'm doing wrong? Here is a sample output:

I'm thinking out to 10 decimal places. Good luck.

Make a guess: 1.14981949962
Make another guess: 1.14981949963
Make another guess:

Here is my code:

# Number guessing game
# The computer will choose a number between 1 and 2 (to ten decimal places)
# and the player will try to guess the number. The program will tell the
# player the number is either higher or lower than the number they guessed.
import random
import os
print "\nWelcome to 'Guess My Number'!"
print "\nI'm thinking of a number between 1 and 2."
print "\nYes, that's right. Between 1 and 2."
print "\nYou have heard of decimals right? Well, I'm"
print "\nthinking out to 10 decimal places. Good luck.\n"
# set random value
number = random.random() + 1
print number
guess = float(raw_input("Make a guess: "))
tries = 1
# the guess loop
while (guess != number):
    if (guess > number):
        print "Lower..."
        print "Higher..."
    guess = float(raw_input("Make another guess: "))
    tries += 1
print "Congratulations! You guessed my number! The number was", number
print "It took you only", tries, "tries!\n"
# end


Please avoid sending me Word or PowerPoint attachments.
See http://www.gnu.org/philosophy/no-word-attachments.html

More information about the Tutor mailing list