All the IPython Notebooks in this example series by Dr. Milan Parmar are available @ GitHub
In this example, you will learn to create a countdown timer.
To understand this example, you should have the knowledge of the following Python programming topics:
# Example 1: Countdown time in Python
import time
def countdown(time_sec):
while time_sec:
mins, secs = divmod(time_sec, 60)
timeformat = '{:02d}:{:02d}'.format(mins, secs)
print(timeformat, end='\r')
time.sleep(1)
time_sec -= 1
print("stop")
countdown(5)
'''
>>Expected output:
00:05
00:04
00:03
00:02
00:01
stop1
'''
stop1
'\n>>Expected output:\n \n00:05\n00:04\n00:03\n00:02\n00:01\nstop1\n'
Explanation:
The divmod()
method takes two numbers and returns a pair of numbers (a tuple) consisting of their quotient and remainder.
end='\r'
overwrites the output for each iteration. The value of time_sec
is decremented at the end of each iteration.