2012-11-22 77 views
-1

我做了一個小數猜測遊戲,如果需要,我已經讓它重新啓動。 然而,它會重新開始並重新開始詢問「myname」,我該如何使它回到它認爲數字的那一點,並且記得我第一次的名字?轉到while循環的某個部分

import random 
restart = '1' 
def main(): 
    guessestaken = 0 

    print ('Hello, what is your name?') 
    myname = raw_input() 


    number = random.randint(1, 50) 
    print ('Okay ' + myname + ', I am thinking of a number between 1 and 50. You have 5 guesses.') 

    while guessestaken < 5: 
     print ('Take a guess.') 
     guess = input() 
     guess = int(guess) 

     guessestaken = guessestaken + 1 

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

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

     if guess == number: 
      break 

    if guess == number: 
     guessestaken = str(guessestaken) 
     print ('Good job ' + myname + ', you got the correct answer in ' + guessestaken + ' guesses') 


    if guess != number: 
     number = str(number) 
     print ('Oh dear ' + myname + ', the number I was thinking of was ' + number + '.') 

while restart == '1': 
    main() 
    restart = raw_input('Would you like to try again? Press 1 for Yes, and 2 for No: ') 

此刻它再次要求我的名字。我的意思是,它是功能性的,只是令人討厭。

感謝

+2

你爲什麼不多種功能拆分起來,每問一個問題,只是重複那些要重複? (例如,將名稱分解爲單獨的函數,並且在while循環之前調用它) – poke

回答

1

你可以簡單地在main()功能前移到

print ('Hello, what is your name?') 
myname = raw_input() 

,所以它只能運行一次。

您還可以在您的main()函數中使用raw_input()而不是input()

+0

他可能使用Python 3,在這種情況下,'input'將會很好。 – Junuxx

+0

@Junuxx:不,他不是。他在腳本的最後一行調用'raw_input()'。 –

+0

+1因爲你的答案是第一位的。 – Junuxx

0

最簡單的方法是詢問main()函數以外的名稱,然後將其傳入每個遊戲。你在技術上不必傳遞它(python仍然可以訪問變量),但最好這樣做。

def main(myname): 
    # Remove the name prompt from here 

... 

print ('Hello, what is your name?') 
myname = raw_input() 

while restart == '1': 
    main(myname) 
    restart = raw_input('Would you like to try again? Press 1 for Yes, and 2 for No: ') 
0

一個簡單的解決將是初始化mynamemain,通過把myname = ''剛下restart = '1'。然後,只要求玩家的名字,如果他的名字是未知的,即:

if myname == '': 
    print ('Hello, what is your name?') 
    myname = raw_input()