python - Python - 在用户输入 n 秒后重复功能
问题描述
我的任务是创建一个程序,如果房子里的温度低于 16°C,它将打开加热器,如果超过 16°C,它将关闭它。我决定让它有点用处并导入计时器。我想知道如何在用户输入“n”时间后重复功能,允许打开或关闭加热器。我目前的代码是:
import time
import random
def main():
temp = random.randint(-15, 35)
print("Current temperature in the house:", temp,"°C")
time.sleep(1)
if temp <= 16:
print("It's cold in the house!")
t = input("How long should the heating work? Enter time in 1.00 (hours.minutes) format:")
print("Heating will work for:", t)
print("House Heating status: ON")
time.sleep() //The timer should start here for the time entered by the user
if temp > 16 and temp <= 25:
print("House Heating status: OFF")
if temp => 26:
print("House Cooler status: ON")
main()
我应该使用哪种技术来添加此计时器?
解决方案
假设您的main
函数已经处理了对的调用time.sleep
,一个简单的反复重复的方法是将您的函数置于无限循环中:
while True:
main()
另一种方法是让你的main
函数返回一个整数,表示要等多久才能再次调用它。这将等待与主逻辑分离。
def main():
...
t = input("How long should the heating work? Enter time in 1.00 (hours.minutes) format:")
...
return int(t)
while True:
wait_time = main()
time.sleep(wait_time)
推荐阅读
- c# - 是否可以建立一个 Func 的集合
- sql - 在谷歌大查询中获得完全加入,在大查询中保持所有频率组合,让我只为所有类型的加入提供左加入
- oracle - 如何忽略分层查询中特定类型的直接父级
- macos - brew update 错误:/usr/local 目录不可写。sudo chown -R $(whoami):admin /usr/local 不工作
- shell - 如何在Jenkinsfile中传递jq参数
- java - 为什么我的吸气剂应该返回对象数组时返回 [LSubmarine;@27c170f0
- monitor - HTC Vive 作为第二台显示器
- c# - Xamarin.Forms iOS Picker 在关闭对话框后跳转到最后一项
- php - 如何在结束 head 标签之前加载多个 css 文件?
- ruby - 无法在 ubuntu vps 上通过 rbenv 安装 ruby 2.5.1