2015-10-30 286 views
0

代碼工作正常,但我無法弄清楚如何完全重新啓動程序。我繼續在代碼中,並且我知道這是不正確的,因爲我希望它在您猜到正確的數字後完全重新啓動,並顯示'恭喜!你猜猜我的電話號碼。Python隨機數生成器

import random 

guesses = 0 
number = random.randint(1, 100) 
print('I am thinking of a number between 1 and 100.') 

while guesses < 100: 
    guess = int(input('Guess? ')) 


    guesses = guesses + 1 

    if guess < number: 
     print('Your guess is too low.') 

    if guess > number: 
     print('Your guess is too high.') 

    if guess == number: 
     continue 

if guess == number: 
    guesses = str(guesses) 
    print('Congratulations! You guessed my number in ' + guesses + '  guesses!') 
+0

只是把整個東西放在一個while循環像「while True」,然後問他們是否他們如果答案不是,請繼續並中斷 – gkusner

+0

感謝您的幫助,此解決方案可以工作,但我希望程序自動重啓。 – Aaron

回答

0

如果你想保持猜測和啓動遊戲自動,你需要做一個遞歸調用:

import random 

def guess_func(): 
    number = random.randint(1, 100) 
    guesses = 0 
    while True: 
     guess = int(raw_input("Enter your guess: ")) 
     if guess < number: 
      print('Your guess is too low.') 
      guesses += 1 

     if guess > number: 
      print('Your guess is too high.') 
      guesses += 1 

     if guess == number: 
      print "Congratulations! You guessed my number in [{}] guesses".format(guesses) 
      print "Let's keep on guessing!" 
      return guess_func() 

guess_func() 
+0

感謝您的幫助改變了我的代碼以適應這種格式,但我注意到的一件事是,除非您將def guess_func下的猜測更改爲1,否則最後一條語句中的猜測次數將會減少一次。 – Aaron

0

所以這樣的:

while True: 
    guesses = 0 

    while guesses < 100: 
     if guesses == 100: 
      break 
      ... 
     if guess == number: 
      print ... 

    yorn = input "do you want to try again?") 
    if yorn == 'n': 
     break 

所以只是包裝你的代碼外,同時,很明顯我跳過了很多代碼的