[Tutor] random number generator

Jim Hutchinson jim at ubuntu-rocks.org
Sat Oct 6 19:19:07 CEST 2007


Greetings all,

It seems I forgot to subscribe to the list so I didn't receive any of
the replies. However, I did check the archive and found all of the
very helpful suggestions. Thanks for your time.

Based on the replies I was able to get this to more or less work.
However, one problem still exists. If you guess a number that is
slightly larger than the random number it evaluates to correct

For example:

----
The number is 1.78889511441
Make a guess: 1.788895114455

Congratulations! You guessed my number! The number was 1.78889511441

It took you only 1 tries!
---

Or even:

---
1.36344601965
Make a guess: 1.3634460196

Congratulations! You guessed my number! The number was 1.36344601965

It took you only 1 tries!
---

I'm also unclear as to how it is choosing a random number out to 10
decimal places. Is that the default and it's just coincidence that I
chose 10? What if I want a random number to 20 decimal places or five?

Here is the 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
os.system("clear")
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
random.seed()
number = random.random() + 1
print number
guess = float(raw_input("Make a guess: "))
tries = 1
# the guess loop
while (abs(number-guess) > 0.0000000001):
    if guess > number:
        print "Lower..."
    elif guess < number:
        print "Higher..."
    tries += 1
    if guess != number:
        guess = float(raw_input("Make another guess: "))
print "\nCongratulations! You guessed my number! The number was", number
print "\nIt took you only", tries, "tries!\n"
# end

Thanks again,
Jim
-- 
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