2012-01-10 52 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) 您甚至可以讓用戶預設最大值。