如何在 Python 中重新运行代码? [英] How do I re-run code in Python?

查看:60
本文介绍了如何在 Python 中重新运行代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个词 un-scrambler 游戏,它只在 CMD 或 python shell 中运行.当用户猜对或不正确时,它会说按任意键再次播放"

I have this word un-scrambler game that just runs in CMD or the python shell. When the user either guesses the word correctly or incorrectly it says "press any key to play again"

我如何让它重新开始?

推荐答案

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

Don't have the program exit after evaluating input from the user; instead, do this in a loop. For example, a simple example that doesn't even use a function:

phrase = "hello, world"

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

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

This outputs the following, with my user input shown as well:

Guess the phrase: a guess
Incorrect.
Guess the phrase: another guess
Incorrect.
Guess the phrase: hello, world
Correct

这显然很简单,但逻辑听起来就像您所追求的那样.一个稍微复杂一点的版本,其中定义了函数供您查看您的逻辑适合的位置,可能是这样的:

This is obviously quite simple, but the logic sounds like what you're after. A slightly more complex version of which, with defined functions for you to see where your logic would fit in, could be like this:

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

输出是相同的.

这篇关于如何在 Python 中重新运行代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆