Tunnelvisionz Tunnelvisionz - 4 years ago 100
Python Question

Countdown Clock: 01:05

How can I create a countdown clock in Python that looks like 00:00 (min & sec) which is on a line of its own. Every time it decreases by one actual second then the old timer should be replaced on its line with a new timer that is one second lower:

01:00
becomes
00:59
and it actually hits
00:00
.

Here is a basic timer I started with but want to transform:

def countdown(t):
import time
print('This window will remain open for 3 more seconds...')
while t >= 0:
print(t, end='...')
time.sleep(1)
t -= 1
print('Goodbye! \n \n \n \n \n')

t=3


I also want to make sure that anything after
Goodbye!
(which would most likely be outside of the function) will be on its own line.

RESULT:
3...2...1...0...Goodbye!


I know this is similar to other countdown questions but I believe that it has its own twist.

Answer Source

Apart from formatting your time as minutes and seconds, you'll need to print a carriage return. Set end to \r:

import time

def countdown(t):
    while t:
        mins, secs = divmod(t, 60)
        timeformat = '{:02d}:{:02d}'.format(mins, secs)
        print(timeformat, end='\r')
        time.sleep(1)
        t -= 1
    print('Goodbye!\n\n\n\n\n')

This ensures that the next print overwrites the last line printed:

countdown

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download