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 list()
Python Program to Append to a File
Python any()
Python Machine Learning Eqution Reference - Sebastian Raschka
Python map()
Python Errors and Built-in Exceptions
Python Program to Check If a List is Empty
Python Program to Randomly Select an Element From the List
Python Program to Print Output Without a Newline
Python Program to Remove Duplicate Element From a List
Python format()
Python chr()
Python List copy()
Python Program to Trim Whitespace From a String
Python hex()
Python Machine Learning Third Edition - Sebastian Raschka & Vahid Mirjalili
Python Generators
Python Matrices and NumPy Arrays
How to Get Started With Python?
Python dict()
Python String encode()
Python Program to Convert Decimal to Binary, Octal and Hexadecimal
Python List index()
Python id()
Python Program to Convert String to Datetime
Python Machine Learning Second Edition - Sebastian Raschka & Vahid Mirjalili
Python String join()
Python Program to Get File Creation and Modification Date
Python min()
Deep Learning with Python - A Hands-on Introduction - Nikhil Ketkar
Python input()
Python set()