1 min read

Python Countdown Timer

This utility creates a simple countdown timer that updates in real-time on the command line. It demonstrates the use of the time module and carriage returns (\r) to overwrite the previous output line.

Modules Used:

  • time: To handle the delay between seconds.

The Code

Save this as timer.py.

import time

def countdown(t):
    """
    Counts down from t seconds.
    """
    while t:
        # Calculate minutes and seconds
        mins, secs = divmod(t, 60)

        # Format as MM:SS
        timer = '{:02d}:{:02d}'.format(mins, secs)

        # Print the time, overwriting the previous line
        # end="\r" moves the cursor back to the start of the line
        print(timer, end="\r")

        time.sleep(1)
        t -= 1

    print('Timer completed!')

if __name__ == "__main__":
    try:
        t = input("Enter the time in seconds: ")
        countdown(int(t))
    except ValueError:
        print("Please enter a valid integer.")
    except KeyboardInterrupt:
        print("\nTimer stopped.")

Usage

python timer.py

programming/python/python