如何在Python中重新运行代码?

Bre*_*ing 1 python python-3.x

我有一个仅在CMD或python shell中运行的单词解扰游戏。当用户正确或错误地猜出单词时,会说“按任意键再次播放”

我将如何重新开始?

Ric*_*ano 5

评估用户的输入后没有退出程序;而是循环执行此操作。例如,一个甚至不使用函数的简单示例:

phrase = "hello, world"

while input("Guess the phrase: ") != phrase:
    print("Incorrect.")  # Evaluate the input here
print("Correct")  # If the user is successful
Run Code Online (Sandbox Code Playgroud)

输出以下内容,同时显示我的用户输入:

phrase = "hello, world"

while input("Guess the phrase: ") != phrase:
    print("Incorrect.")  # Evaluate the input here
print("Correct")  # If the user is successful
Run Code Online (Sandbox Code Playgroud)

这显然很简单,但是逻辑听起来像您所追求的。稍微复杂一些的版本,其中包含定义的功能供您查看逻辑适合的位置,如下所示:

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()
Run Code Online (Sandbox Code Playgroud)

输出是相同的。

  • 您第三次尝试都没有任何线索,哇+1!; P (4认同)

Har*_*pta 5

甚至下面的风格也有效!

一探究竟。

def Loop():
    r = raw_input("Would you like to restart this program?")
        if r == "yes" or r == "y":
            Loop()
        if r == "n" or r == "no":
            print "Script terminating. Goodbye."
    Loop()
Run Code Online (Sandbox Code Playgroud)

这是 重复执行函数(语句集)的方法

希望你喜欢 :) :} :]

  • 要使其在 python 3.x 中运行,请将 `raw_input` 更改为 `input` (3认同)