python - 只有一个提示的真正循环
问题描述
我写了一段带有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()
解决方案
您正试图让用户中断无限循环。您的想法使用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
。
推荐阅读
- java - Spring MVC 在 WAR 和 JAR 文件中带有 jsp 文件
- php - 试图验证 JWT 签名 Tymon/jwt-auth laravel
- python - 使用 BeautifulSoup Python 进行 Web 抓取返回 None
- r - R:基于超过 1 个变量对记录进行分类
- python - 在 Python 中打印某些 JSON 数据
- android - 如何查看应用内购买的促销代码是否已兑换?
- javascript - POST https://accounts.spotify.com/api/token 415 Unsupported Media when using fetch
- angular - 测试失败“预期的间谍 doDeleteRule 已被调用。”,茉莉,业力
- android - Cordova Javascript QR 扫描仪插件无法在 Android 上运行 (cordova-plugin-qrscanner)
- amazon-web-services - 通过 java 创建 AWS Amazon Polly mp3 文件