[英]Python - repeat function after n seconds inputted by user
我的任務是創建一個程序,如果室內溫度低於 16°C,它將打開加熱器,如果超過 16°C,則將其關閉。 我決定讓它有點用處並導入計時器。 我想知道如何在用戶輸入“n”次后重復 function,它允許打開或關閉加熱器。 我當前的代碼是:
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
已經處理了對 time.sleep 的調用,一個簡單的重復方法是將您的 function 置於無限循環中:
while True:
main()
另一種方法是讓您的main
function 返回一個 integer 等待多長時間,直到再次調用它。 這將等待與主要邏輯分離。
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.