Open In App

How To Create a Countdown Timer Using Python?

Last Updated : 09 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

  • Use divmod(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 using end=’\r’ to overwrite the previous output.
  • Pause the loop for 1 second using time.sleep(1).
  • Decrease t by 1 each iteration.

7. After the loop finishes, print “Fire in the hole!!” to indicate the timer has ended.

Python Code: Countdown Timer

Python
import time

def countdown(t):
    while t:
        mins, secs = divmod(t, 60)
        timer = '{:02d}:{:02d}'.format(mins, secs)
        print(timer, end='\r')  # Overwrite the line each second
        time.sleep(1)
        t -= 1

    print("Fire in the hole!!")

t = input("Enter the time in seconds: ")

countdown(int(t))

Output: 


Next Article

Similar Reads