top of page

Data Scientist Program


Free Online Data Science Training for Complete Beginners.

No prior coding knowledge required!

Countdown timer in Python

In this article, we are going to see how we can write a countdown timer with python. Lets first review the whole bunch of code and look deeper into each piece.

import time

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


So basically, the first statement imports the time module which is shipped with Python. This module provides various time-related functions.

The function accepts an integer which is the time in seconds the functions starts counting down from. Out of the module's methods, the time.sleep function is used in this function to add an interval of 1 second before the next iteration is executed in the loop.

The other python built-in method used here is the divmod() function, which takes two numbers and returns a pair of numbers (a tuple) consisting of their quotient and remainder. In our code, it is specifically used to calculate the minutes and second part of the function's output at each iteration.


Recent Posts

See All


bottom of page