我做了一個小數猜測遊戲,如果需要,我已經讓它重新啓動。 然而,它會重新開始並重新開始詢問「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: ')
此刻它再次要求我的名字。我的意思是,它是功能性的,只是令人討厭。
感謝
你爲什麼不多種功能拆分起來,每問一個問題,只是重複那些要重複? (例如,將名稱分解爲單獨的函數,並且在while循環之前調用它) – poke