IDLE-Python:回到某一行,我该怎么做?

2024-06-06 12:26:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经创建了一个选择菜单,要求您输入要运行的命令,我已经通过使用ifelif语句完成了这项工作,但是当命令(if语句)完成时,我希望它们转到询问要运行哪个命令的行。这是我目前掌握的代码(目前我还没有这样做的代码):


# Asks which command you want to run.
word = input("Which command? ")

# Runs the command/s.

if word == "info":
    print("Info command.")

elif word == "replace":
    print("Replace command.")

elif word == "ping":
    print("Ping command")

else:
    print("Command not found")

如果有人能帮忙,那就太棒了,谢谢。


Tags: torun代码命令youwhichif菜单
2条回答

很抱歉,如果这太多,但您可能需要考虑将其放入一个函数中来执行以下操作:

def main():
    # Asks which command you want to run.
    word = input("Which command? ").strip().lower()

    # Runs the command/s.

    if word == "info":
        print("Info command.")

    elif word == "replace":
        print("Replace command.")

    elif word == "ping":
        print("Ping command")

    elif word == "quit":
        return False

    else:
        print("Command not found")
    return True

while main():
    pass

这和while True然后if something: break是一样的

尝试将代码包装到一个while True:块中。这将无限期地重复代码。

如需进一步阅读,请尝试this

相关问题 更多 >