2015-09-28 81 views
3

我正在python 3上做一個程序。我有一個地方,我需要重新啓動腳本。我怎樣才能做到這一點。如何重新啓動我的python 3腳本?

#where i want to restart it 
name= input("What do you want the main character to be called?") 
gender = input("Are they a boy or girl?") 

if gender == "boy": 
    print("Lets get on with the story.") 
elif gender == "girl": 
    print("lets get on with the story.") 
else: 
    print("Sorry. You cant have that. Type boy or girl.") 
    #restart the code from start 

print("Press any key to exit") 
input() 

回答

3

這是關於編程的不特定Python ......由可以縮短與boygirl兩個條件你的代碼的方式一般問題...

while True: 
    name= input("What do you want the main character to be called?") 
    gender = input("Are they a boy or girl?") 

    if gender == "boy" or gender == "girl": 
     print("Lets get on with the story.") 
     break 

    print("Sorry. You cant have that. Type boy or girl.") 

print("Press any key to exit") 
input() 
+0

謝謝。這是完美的 –

+0

無後顧之憂,樂意幫忙! –

0

簡單但不好解決方案,但你明白了。我相信,你可以做得更好。

while True: 
    name= input("What do you want the main character to be called?") 
    gender = input("Are they a boy or girl?") 

    if gender == "boy": 
     print("Lets get on with the story.") 
    elif gender == "girl": 
     print("lets get on with the story.") 
    else: 
     print("Sorry. You cant have that. Type boy or girl.") 
     #restart the code from start 

    restart = input("Would you like to restart the application?") 
    if restart != "Y": 
     print("Press any key to exit") 
     input() 
     break 
0

在評估用戶的輸入後沒有程序退出;相反,做一個循環。例如,甚至沒有用到的功能一個簡單的例子:顯示

phrase = "hello, world" 

while (input("Guess the phrase: ") != phrase): 
    print("Incorrect.") //Evaluate the input here 
print("Correct") // If the user is successful 

這將輸出以下,用我的用戶輸入,以及:

Guess the phrase: a guess 
Incorrect. 
Guess the phrase: another guess 
Incorrect. 
Guess the phrase: hello, world 
Correct 

,或者你可以有兩個單獨的函數寫它與上面相同(只是它被寫成兩個單獨的功能):

def game(phrase_to_guess): 
return input("Guess the phrase: ") == phrase_to_guess 

def main(): 
    phrase = "hello, world" 
    while (not(game(phrase))): 
     print("Incorrect.") 
    print("Correct") 

main() 

希望這是你在找什麼。