我的任务是创建一个程序,如果房间里的温度低于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()我应该使用哪种技术来添加此计时器?
发布于 2020-11-15 05:26:01
假设您的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)https://stackoverflow.com/questions/64838661
复制相似问题