Countdown Timer in PythonPixelpy-Python programming with source code

Countdown Timer in Python

 Countdown Timer in Python

A countdown timer is a Python program that counts from a certain time interval (such as hours, minutes, or seconds) to zero. When the countdown hits zero, it usually alerts the user. The timer shows the remaining time in real time, updating every second.

Key Features of a Countdown 

TimerTakes User Input: The user inputs the value of the countdown duration (e.g., 1 hour, 30 minutes, and 15 seconds).


Displays Time in Real-Time: The timer updates every second, showing the remaining time in a readable format (e.g., HH:MM: SS).


Countdown to Zero: The timer decrements the time until it reaches zero.


Notification: When the countdown ends, the program notifies the user (e.g., by printing a message or playing a sound).


How Does a Countdown Timer Work in Python?

Convert Time to Seconds:

  • The user inputs hours, minutes, and seconds.
  • These values are converted into total seconds for easier calculation.


Loop Through the Countdown:

  • A loop runs for the total number of seconds.
  • Inside the loop, the program.
  • Converts the remaining seconds back into HH:MM: SS format.
  • Displays the time.
  • Waits for 1 second using time. sleep(1).Decrements the total seconds by 1.


Display the Final Message:

When the countdown reaches zero, the program prints a message like "Time's up!"

Here’s a simple implementation of a countdown timer in Python:

Python Code


import time

def countdown(total_seconds):
    while total_seconds >= 0:
        # Convert total seconds into hours, minutes, and seconds
        hours = total_seconds // 3600
        remaining = total_seconds % 3600
        minutes = remaining // 60
        seconds = remaining % 60

        # Wait for 1 second
        time.sleep(1)

        # Decrease the total time by 1 second
        total_seconds -= 1

    # Display the time in HH:MM:SS format
    print(f"{hours:02}:{minutes:02}:{seconds:02}", end='\r')

    # Print a message when the countdown is complete
    print("\nTime's up!")

def get_user_input():
    hours = int(input("Enter hours: "))
    minutes = int(input("Enter minutes: "))
    seconds = int(input("Enter seconds: "))

    # Convert everything to total seconds
    total_seconds = hours * 3600 + minutes * 60 + seconds
    return total_seconds

if __name__ == "__main__":
    print("Welcome to the Countdown Timer!")
    total_seconds = get_user_input()
    print(f"Starting countdown from {total_seconds} seconds...")
    countdown(total_seconds)

Code Output


Welcome to the Countdown Timer!
Enter hours: 00
Enter minutes: 00
Enter seconds: 10
Starting countdown from 10 seconds...
00:00:00
Time's up!

#buttons=(Ok, Go it!) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Ok, Go it!