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:
- Python while Loop
- Python divmod()
- Python time Module
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)
- 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_secis decremented at the end of each iteration.
Related posts:
Python Set clear()
Python Set isdisjoint()
Python String islower()
Python @property decorator
Python int()
Python List count()
Python List index()
Python Program to Get Line Count of a File
Introduction to Scientific Programming with Python - Joakim Sundnes
Python Functions
Python Machine Learning Third Edition - Sebastian Raschka & Vahid Mirjalili
Python List reverse()
Python String capitalize()
Python Program to Parse a String to a Float or Int
Python Program to Swap Two Variables
Natural Language Processing with Python - Steven Bird & Ewan Klein & Edward Loper
Python ascii()
Python Program to Check If a String Is a Number (Float)
Python Program to Check If Two Strings are Anagram
Python Program to Access Index of a List Using for Loop
Python String isnumeric()
Python String rindex()
Python open()
Python next()
Python String isdigit()
Python filter()
Python Package
Python bin()
Python pass statement
Python compile()
Python Program to Get the Class Name of an Instance
Python Input, Output and Import