Skip to main content
 首页 » 编程设计

python之如何在 Python 中重新运行代码

2025年05月04日13think

我有这个 word un-scrambler 游戏,它只在 CMD 或 python shell 中运行。当用户猜对或猜错时,系统会提示“按任意键再次播放”

我怎样才能让它重新开始?

请您参考如下方法:

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

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

输出是相同的。