I'm trying to write a program which generates a pseudo-random number and allows the user to guess it. When the user guesses the number wrong, as is most likely, I would like the function to return to the beginning of the conditional loop, not the very beginning of the function (which would cause it to generate a new pseudo-random number). Here's what I have so far:
def guessingGame():
import random
n = random.random()
input = raw_input("Guess what integer I'm thinking of.")
if int(input) == n:
print "Correct!"
elif int(input) < n:
print "Too low."
guessingGame()
elif int(input) > n:
print "Too high."
guessingGame()
else:
print "Huh?"
guessingGame()
How could make the pseudo-random number locally immutable so that after a wrong guess the number would not change?
解决方案from random import randint
def guessingGame():
n = randint(1, 10)
correct = False
while not correct:
raw = raw_input("Guess what integer I'm thinking of.")
if int(i) == n:
print "Correct!"
correct = True
elif int(i) < n:
print "Too low."
elif int(i) > n:
print "Too high."
else:
print "Huh?"
guessingGame()