Google News
logo
Python Program to Create a Countdown Timer
Here's an example Python code that creates a countdown timer :
Program :
import time

def countdown_timer(seconds):
    while seconds:
        mins, secs = divmod(seconds, 60)
        timeformat = '{:02d}:{:02d}'.format(mins, secs)
        print(timeformat, end='\r')
        time.sleep(1)
        seconds -= 1

    print('Time is up!')

countdown_timer(60) # countdown for 60 seconds
In this code, we define a function called `countdown_timer` that takes one argument `seconds`, which is the number of seconds to count down from.

Inside the function, we use a `while` loop to keep counting down until `seconds` becomes zero. Inside the loop, we use the `divmod()` function to calculate the number of minutes and seconds remaining, and then format the result as a string using the `format()` method.

We then print the formatted string using the `print()` function with `end='\r'` to keep the cursor on the same line.

We then use the `time.sleep()` function to pause the program for one second, and decrement `seconds` by one.

Finally, when the loop ends (i.e., when `seconds` becomes zero), we print a message to indicate that the countdown is over.

To run this code, simply call the `countdown_timer()` function with the number of seconds you want to count down from as the argument. In the example code, we count down from 60 seconds.