Alexander Urum
Alexander Urum

Reputation: 131

Python - repeat function after n seconds inputted by user

My task is to create a program, which will turn heater on if temperature in the house is less than 16°C or turning it off if it's more than 16°C. I decided to make it a bit useful and import the timer. I want to know how is it possible to repeat function, which allows to turn heater on or off, after "n" time inputted by user. My current code is:

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()

Which technique should I use to add this timer?

Upvotes: 1

Views: 141

Answers (1)

sytech
sytech

Reputation: 41209

Assuming your main function handles the call to time.sleep already, a simple way to repeat over and over would be to put your function in an infinite loop:

while True:
    main()

Another way would be to have your main function return an integer of how long to wait until it should be called again. This decouples the waiting from the main logic.

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)

Upvotes: 2

Related Questions