我正在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()
答案 0 :(得分:3)
通过Python
和boy
上的两个条件来缩短代码的方式,这是一个关于编写非特定于girl
的一般问题... / p>
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()
答案 1 :(得分: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
答案 2 :(得分: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()
希望这就是你要找的东西。