首页 > 解决方案 > 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()

我应该使用哪种技术来添加此计时器?

标签: pythonpython-3.x

解决方案


假设您的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)

推荐阅读