python中的时钟倒计时计算
我想写一个名为python中的时钟倒计时计算,python,loops,counter,clock,Python,Loops,Counter,Clock,我想写一个名为boom(h,m,s)的函数,在main的输入开始在HH:MM:SS中打印后,格式化倒计时时钟,然后打印“boom”。 除了time.sleep()之外,我不允许使用现有模块,因此我必须基于While\For循环 import time def boom(h,m,s): while h>0: while m>0: while s>0: print ("%d:%d:%d"%(h,m,s
boom(h,m,s)
的函数,在main的输入开始在HH:MM:SS中打印后,格式化倒计时时钟,然后打印“boom”。除了time.sleep()之外,我不允许使用现有模块,因此我必须基于While\For循环
import time
def boom(h,m,s):
while h>0:
while m>0:
while s>0:
print ("%d:%d:%d"%(h,m,s))
time.sleep(1)
s-=1
print ("%d:%d:%d"%(h,m,s))
time.sleep(1)
s=59
m-=1
print ("%d:%d:%d"%(h,m,s))
time.sleep(1)
s=59
m=59
h-=1
while h==0:
while m==0:
while s>0:
print ("%d:%d:%d"%(h,m,s))
time.sleep(1)
s-=1
print ("BooM!!")
我知道如何计算秒数部分,但当我在H和M参数上输入零时,它会干扰时钟。只需将其全部转换为秒数,然后在打印时将其转换回
def hmsToSecs(h,m,s):
return h*3600 + m*60 + s
def secsToHms(secs):
hours = secs//3600
secs -= hours*3600
mins = secs//60
secs -= mins*60
return hours,mins,secs
def countdown(h,m,s):
seconds = hmsToSecs(h,m,s)
while seconds > 0:
print "%02d:%02d:%02d"%secsToHms(seconds)
seconds -= 1
sleep(1)
print "Done!"
问题在于:
while h==0:
while m==0:
while s>0:
如果m==0
,并且s==0
while循环不会中断,因此存在一个无限循环。只需在最里面的
中添加一个else子句,如下所示:
while s>0:
...
else: # executed once the above condition is False.
print ('BooM!!')
return # no need to break out of all the whiles!!
我改了。。。我并没有一开始就读它:PYou没有打印“BooM!!”
:)如果m==0和s==0,它不会进入循环吗?让我们假设m==0
,那么你进入while循环,一旦s>0
的条件为False,内部while结束,但我们仍然在外部while,那么我们进入一个无限循环,在s>0之后发生的是False。如果m==0
,则输入我们不退出的m
while循环:)如果我不清楚,请使用调试器,您应该理解ndahh-duh(我相信我没有注意到):+1。。。特别是你不像我,你不只是帮他做作业