2012-01-10 46 views
0

我正在尝试编写一个程序来生成一个伪随机数并允许用户猜测它。当用户猜测数字错误时,我最希望函数返回到条件循环的开始处,而不是函数的开始部分(这会导致它产生一个新的伪随机数)。这是我到目前为止有:用Python猜数字游戏的控制循环

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

如何才能让伪随机数不变本地从而使错误的猜测后的数字会不会有变化?

+4

我不知道任何可以做你想做的任何编程语言。 – 2012-01-10 01:07:11

+3

您已将此问题标记为'loops'。所以你似乎知道答案已经是... – 2012-01-10 01:07:56

+1

除BASIC外! GOTO赢得胜利! – 2012-01-10 01:08:34

回答

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

啊,一段时间循环。谢谢。 – sdsgg 2012-01-10 01:14:39

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之间的浮点数,并且您的代码看起来像是期望值和整数。

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

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