[Tutor] How to enable pausing my stop_watch.py ?

Dick Moores rdm at rcblue.com
Tue Jul 6 12:08:55 CEST 2004


See script below.

I would like to enable pausing and then resuming stop_watch.py. For 
example, say I've set it to beep after 30 minutes. I start it, but then 
discontinue the activity I'm timing. I want to pause the stopwatch by 
pressing a key and then resume later by pressing (another?) key, just as 
I could do with a real stopwatch. Is this possible?

And I'd also really appreciate a close critique of the code I have so far.

"""
# stop_watch.py
import time, winsound

def hms(seconds):
     """Convert seconds to tuplet (hours, minutes, seconds)"""
     import time
     hours, minutes = 0, 0

     if seconds >= 60 and seconds < 3600:
         minutes = divmod(seconds,60)[0]
         seconds = divmod(seconds,60)[1]
     elif seconds >= 3600:
         hours = divmod(seconds,3600)[0]
         seconds = divmod(seconds,3600)[1]
         minutes = divmod(seconds,60)[0]
         seconds = divmod(seconds,60)[1]

     return hours, minutes, seconds # returns a tuple, e.g. (1, 40, 8.5)


hours = raw_input("Enter the number of hours to time ")
if hours == "":
     h_seconds = 0
else:
     h_seconds = 3600 * int(hours)

minutes = raw_input("And the number of minutes ")
if minutes == "":
     m_seconds = 0
else:
     m_seconds = 60 * int(minutes)

seconds = raw_input("And the number of seconds ")
t0 = time.time()
if seconds == "":
     seconds = 0
seconds = h_seconds + m_seconds + int(seconds)
print "Seconds total is", seconds

t = hms(seconds)
print "Beep will sound after %d hours %d minutes %d seconds\n"  \
       % (t[0], t[1], t[2])

r = 10 # get report of time-passed and time-left every r seconds
k = r
while True:
     t1 = time.time()
     seconds_passed = t1 - t0
     seconds_left = seconds - int(seconds_passed)

     if seconds_passed >= seconds:
         break

     if seconds_passed > k:
         p = hms(seconds_passed)
         l = hms(seconds_left)
         print "%d hours %d minutes %d seconds have passed" \
               % (p[0], p[1], p[2])
         print "%d hours %d minutes %d seconds are left\n" \
               % (l[0], l[1], l[2])
         k += r

print "seconds elapsed:", (t1 - t0) # as a check on accuracy
print "TIME'S UP!"

# winsound.Beep(frequency, duration in milliseconds) - only for Windows
winsound.Beep(500,5)
"""

Thanks, tutors,

Dick Moores

   



More information about the Tutor mailing list