如何重新启动我的 python 3 脚本?

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 ...顺便说一下,您可以使用 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()

简单但不好的解决方案,但您明白了。我相信,你可以做得更好。

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()

希望这就是您要找的。