Python CountDown Timer - How do I create a Stopwatch in python

Published January 31, 2022

As the name suggests, a stopwatch is simply an application for counting downtime. It is timed in seconds and helps users learn how long it took them to complete a particular task or an event. A countdown timer counts the minutes and seconds until the entered time elapses. The timer accepts the user's time input, and when the timer expires, the countdown instantly stops counting.

In this article, I will show you how to create a countdown timer using Python.

How to create a Python countdown timer

We will use the sleep() function and the time module to create our Python countdown timer. Let's follow the simple steps below to create our Python countdown timer.

Step 1: Firstly, we must install the time module in our application. To import this module, add the following line of code:

import time

Step 2: The countdown timer takes the user time input and starts counting down. In this step, we will implement a code that collects the user time input.

t = input ("Input the Countdown time in seconds: ")

 

Step 3: Create a countdown() function, which counts down the entered time to 0. In order to do this, we will use a while loop that takes the user input and transforms it into a variable.def countdown(t):   

   

while t:

        mins, secs = divmod(t, 60)

        timer = '{:02d}:{:02d}'.format(mins, secs)

        print(timer, end="\r")

        time.sleep(1)

        t -= 1

         print('Timeout!!')

In this function, the while loop will run until it becomes 0. After the time becomes 0, the code will display “Timeout!!” to notify the user. 

The time.sleep() will be used to make the code wait for a period of 1 second.

Step 4: We are finally done. Let’s run our countdown timer application.

Final code

# import the time module

import time

# define the countdown func.

def countdown(t):

while t:

        mins, secs = divmod(t, 60)

        timer = '{:02d}:{:02d}'.format(mins, secs)

        print(timer, end="\r")

        time.sleep(1)

        t -= 1

print('Timeout!!') 

# input time in seconds

t = input("Input the Countdown time in seconds: ")

# function call

countdown(int(t))

 

Python Timer Example

 

 

 

Python count down timer example

Conclusion: In this Python example we will created Python Count Down timer example

 

Download Source code

 

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

319 Views