Control loop for a number-guessing game in Python

2019-06-10 05:11发布

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?

5条回答
一纸荒年 Trace。
2楼-- · 2019-06-10 05:26
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()
查看更多
虎瘦雄心在
3楼-- · 2019-06-10 05:26

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.

查看更多
Fickle 薄情
4楼-- · 2019-06-10 05:34

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.

查看更多
劳资没心,怎么记你
5楼-- · 2019-06-10 05:37

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()
查看更多
不美不萌又怎样
6楼-- · 2019-06-10 05:42

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.

查看更多
登录 后发表回答