[英]python 3.4, timer count down not working
我想創建一個以小時分和秒為單位倒數的時鍾,但是由於某種原因而無法正常工作,有人可以幫我嗎
def countdown():
times = 1
th = 1
tm = 0
ts = 0
while times != 0:
if (ts>0 or tm>0 or th>0):
print ('it run for ' + str(th) + ' Hours ' + str(tm) + ' Minutes ' + str(ts) + ' Seconds ')
time.sleep(1)
ts = ts - 1
if (ts==0 and (tm>0 or th>0)):
ts = 59
tm = tm - 1
if(ts==0 or tm==0 and th>0):
ts = 59
tm = 59
th = th - 1
if (ts==0 and tm==0 and th==0):
times = 0
else:
print ('stopped')
ts = 0
tm = 0
th = 0
countdown()
謝謝
一個簡單得多的方法是使用datetime和time.sleep
在一個函數中,您可以通過天,小時,分鍾和秒來從以下時間倒數:
from datetime import datetime, timedelta
import time
def countdown(d=0, h=0, m=0, s=0):
counter = timedelta(days=d, hours=h, minutes=m, seconds=s)
while counter:
time.sleep(1)
counter -= timedelta(seconds=1)
print("Time remaining: {}".format(counter))
倒數5秒的示例:
In [2]: countdown(s=5)
Time remaining: 0:00:04
Time remaining: 0:00:03
Time remaining: 0:00:02
Time remaining: 0:00:01
Time remaining: 0:00:00
兩個小時:
In [3]: countdown(h=2)
Time remaining: 1:59:59
Time remaining: 1:59:58
Time remaining: 1:59:57
Time remaining: 1:59:56
Time remaining: 1:59:55
Time remaining: 1:59:54
import datetime
import time
def countdown():
count = datetime.timedelta(hours=1)
while count:
print ('it run for ' + str(count))
time.sleep(1)
count -= datetime.timedelta(seconds=1)
print ('stopped')
countdown()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.