【问题标题】:How to fix a while loop that goes on forever in Python?如何修复在 Python 中永远持续的 while 循环?
【发布时间】:2019-10-11 14:41:43
【问题描述】:

我正在尝试创建一个简单的 while 循环,它将运行命令启动、停止、退出和帮助。开始、停止和帮助只会显示一些打印文本。在它们运行之后,我希望它继续执行另一个命令。但是,在退出时,我希望整个程序停止。

input_command = input("> ").lower()

while input_command != "quit":
    print(input_command)
    if input_command == "start":
        print("The car is ready! VROOM VROOM!")
        print(input_command)
    elif input_command == "stop":
        print("Car stopped.")
    elif input_command == "help":
        print("""
        start - starts the car
        stop - stops the car
        quit - exits the program
        """)
else:
    print("Sorry, I don't understand that...")

【问题讨论】:

  • 您永远不会为 input_command 分配新值
  • 您必须在循环中 的某处更改 input_command

标签: python while-loop


【解决方案1】:

您永远不会重新分配输入命令,因此它只需要输入一次,

input_command = ''

while input_command != "quit":
     input_command = input("> ").lower()

【讨论】:

    猜你喜欢
    • 2014-05-30
    • 1970-01-01
    • 1970-01-01
    • 2020-09-15
    • 1970-01-01
    • 1970-01-01
    • 2021-11-18
    • 2022-06-15
    • 1970-01-01
    相关资源
    最近更新 更多