用户输入n秒后Python重复函数

2024-06-16 12:01:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我的任务是创建一个程序,当室内温度低于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()

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


Tags: theinimport程序iftimestatusrandom
1条回答
网友
1楼 · 发布于 2024-06-16 12:01:39

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

相关问题 更多 >