Control loop for a number-guessing game in Python
Question: 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?


Answer: 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:

    
    
    def guessingGame(n=None):
        if n is None:
            import random
            n = random.randint(1, 10)
        input = raw_input("Guess what integer I'm thinking of.")
        if int(input) == n:
            print "Correct!"
        elif int(input) < n:
            print "Too low."
            guessingGame(n)
        elif int(input) > n:
            print "Too high."
            guessingGame(n)
        else:
            print "Huh?"
            guessingGame(n)
    

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 choose `n`, any time after the current `n` is passed into
the call so you don't create a new one.

Note that the call to `random()` was replaced with `randint()`, since
`random()` returns a float between 0 and 1 and your code appears to expect and
integer.

