Sagi
Sagi

Reputation: 75

clock countdown calculation in python

I want to write a function called boom(h,m,s) that after input from main starts printing in HH:MM:SS format the countdown clock, and then prints "boom".
I'm not allowed to use existing modules except the time.sleep(), so I have to base on While\For loops.

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!!")

I figured how to calculate the seconds part, but when I input zeros on H and M parameters, it's messing with the clock.

Upvotes: 0

Views: 1336

Answers (2)

Joran Beasley
Joran Beasley

Reputation: 113978

just convert it all to seconds and convert it back when you print ...

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!"

Upvotes: 0

pradyunsg
pradyunsg

Reputation: 19416

The problem is here:

while h==0:
    while m==0:
        while s>0:

If m == 0, and s == 0 the while loop doesn't break, so there is an infinite loop.
Just add an else clause to the (last and) inner-most while, like so:

while s>0:
    ...
else: # executed once the above condition is False.
    print ('BooM!!')
    return # no need to break out of all the whiles!!

Upvotes: 1

Related Questions