首页 > 解决方案 > 只有一个提示的真正循环

问题描述

我写了一段带有while循环的代码,我想一直运行到用户输入字符串退出。但是,我不希望在每个循环循环后停止循环以重复提示。我怎样才能做到这一点?

目前代码循环正确,但是在 while 循环中它不响应退出一次。

if __name__ == '__main__':
    prog_question = input("Enter exit to quit the heat tracker after a cycle.")
    while name == True:
        if prog_question == "exit":
            name = False
            break
        else:
            temperature_info = measure_temp()
            if temperature_info[1] == "No error":
                if int(temperature_info[0]) < int(check_temp):
                    heater("on",check_period*60)
                else:
                    heater("off",check_period*60)
            else:
                measure_temp()

标签: pythonpython-3.x

解决方案


您正试图让用户中断无限循环。您的想法使用input的缺点是用户需要在每次迭代中实际输入一些内容。

使用它可能更有趣try/except

from time import sleep
try:
    print("Hit Ctrl-C to stop the program")
    while True:
        print("still running")
        sleep(1)
except KeyboardInterrupt:
    print("this is the end")

或者你也可以看看模块signal


推荐阅读