In this article, we will see how to create a countdown timer using Python. The code will take input from the user regarding the length of the countdown in seconds. After that, a countdown will begin on the screen of the format 'minutes: seconds'. We will use the time module here.
Step-by-Step Approach
In this project, we will be using the time module and its sleep() function. Follow the below steps to create a countdown timer:
1. Import the time module using import time.
2.Get user input for countdown duration (in seconds).
3. Convert input to integer (as input() returns a string).
4. Define a function countdown(t) to perform the countdown.
5. Use a while loop to run the countdown until t reaches 0.
6. Inside the loop:
- Usedivmod(t, 60) to convert seconds to minutes and seconds.
- Format the time string using '{:02d}:{:02d}'.format(mins, secs).
- Print the time on the same line usingend='\r' to overwrite the previous output.
- Pause the loop for 1second usingtime.sleep(1).
- Decreaset by1 eachiteration.
7. After the loop finishes, print "Fire in the hole!!" to indicate the timer has ended.
Python Code: Countdown Timer
Pythonimporttimedefcountdown(t):whilet:mins,secs=divmod(t,60)timer='{:02d}:{:02d}'.format(mins,secs)print(timer,end='\r')# Overwrite the line each secondtime.sleep(1)t-=1print("Fire in the hole!!")t=input("Enter the time in seconds: ")countdown(int(t))
Output: