简体   繁体   中英

Control loop for a number-guessing game in Python

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:

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.

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()

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.

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.

from random import randint

class GuessingGame (object):

    n = randint(1,10)

    def prompt_input(self):
        input = raw_input("Guess what integer I'm thinking of: ")
        self.validate_input(input)

    def validate_input(self, input):
        try:
            input = int(input)
            self.evaluate_input(input)

        except ValueError:
            print "Sorry, but you need to input an integer"
            self.prompt_input()

    def evaluate_input(self, input):
        if input == self.n:
            print "Correct!"
        elif input < self.n:
            print "Too low."
            self.prompt_input()
        elif input > self.n:
            print "Too high."
            self.prompt_input()
        else:
            print "Huh?"
            self.prompt_input()

GuessingGame().prompt_input()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM