![](/img/trans.png)
[英]How to restart my Python script if I run it with “python -m”?
[英]How can I restart my python 3 script?
我在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()
這是一個關於編程不是特定於Python
的一般性問題...通過你可以用boy
和girl
的兩個條件來縮短代碼的方式......
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()
簡單但不好的解決方案,但你明白了。 我相信,你可以做得更好。
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
在評估用戶的輸入后,沒有程序退出; 相反,在循環中執行此操作。 例如,一個甚至不使用函數的簡單示例:
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()
希望這是你正在尋找的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.