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?
Although looping here is probably the better way to do this, here is how you can implement it recursively with a very minimal change to your code:
By providing an optional parameter to
guessingGame()
you can get the behavior you want. If a parameter is not provided it is the initial call and you need to randomly choosen
, any time after the currentn
is passed into the call so you don't create a new one.Note that the call to
random()
was replaced withrandint()
, sincerandom()
returns a float between 0 and 1 and your code appears to expect and integer.The simplest thing to do here would probably be to just use a loop here - no recursion.
However if you're set on using recursion, you can just put the conditional into its own function that takes the random number as an argument and can the recursively call itself without recalculating the number.
Creating a class and defining the logic within different methods (aka functions) may be your best bet. Checkout the Python docs for more info on classes.
Import random and generate your random number outside of your function? You may also want to set a range for the generated integers eg
n = random.randint(1,max)
You could even have the user preset the max.