Python中数字猜谜游戏的控制循环

时间:2012-01-10 01:05:04

标签: python loops random recursion

我正在尝试编写一个生成伪随机数的程序,并允许用户猜测它。当用户猜测数字错误时,我很可能会希望函数返回到条件循环的开头,而不是函数的最开头(这将导致它生成一个新的伪随机数)。这是我到目前为止所做的:

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

如何使伪随机数在本地不可变,以便在错误猜测后数字不会改变?

5 个答案:

答案 0 :(得分:3)

尽管在这里循环可能是更好的方法,但是这里是如何通过对代码进行非常小的更改来递归实现它:

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)

通过向guessingGame()提供可选参数,您可以获得所需的行为。如果未提供参数,则它是初始呼叫,您需要在当前n传递到呼叫后的任何时间随机选择n,这样您就不会创建新呼叫。

请注意,对random()的调用已替换为randint(),因为random()返回0到1之间的浮点数,而您的代码似乎是期望和整数。

答案 1 :(得分:1)

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

答案 2 :(得分:0)

这里最简单的做法可能就是在这里使用一个循环 - 没有递归。

但是如果你设置使用递归,你可以将条件放入它自己的函数中,该函数将随机数作为参数,并且可以递归调用自身而不重新计算数字。

答案 3 :(得分:0)

创建一个类并在不同方法(也就是函数)中定义逻辑可能是你最好的选择。 Checkout the Python docs了解有关课程的更多信息。

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

答案 4 :(得分:0)

随机导入并在函数外生成随机数? 您可能还想为生成的整数设置范围 例如n = random.randint(1,max) 您甚至可以让用户预设最大值