How to Create a Countdown Timer in Python

In this tutorial, we will program 'How to Create a Countdown Timer in Python'. We will learn how to create a proper countdown timer. The main goal here is to create a reliable countdown timer that can be used to time any events. I will provide a sample program to demonstrate the actual coding of this tutorial.

This topic is very easy to understand; just follow the instructions I provide, and you can also do it yourself with ease. The program I will show you covers the basics of programming for creating a countdown timer. I will do my best to provide you with the easiest method of creating this countdown timer program. So, let's start with the coding.

Getting Started:

First you will have to download & install the Python IDLE's, here's the link for the Integrated Development And Learning Environment for Python https://www.python.org/downloads/.

Creating Main Function

This is the main function of the application. The following code will display a simple GUI in terminal console that will display the countdown timer. To do this, simply copy and paste these blocks of code into the IDLE text editor.
  1. import time
  2.  
  3. def countdown(time_sec):
  4.     while time_sec:
  5.         mins, secs = divmod(time_sec, 60)
  6.         timeformat = '{:02d}:{:02d}'.format(mins, secs)
  7.         print(timeformat, end='\r')
  8.         print("\n")
  9.         time.sleep(1)
  10.         time_sec -= 1
  11.  
  12.     print("Timer end")
  13.  
  14.  
  15. while True:
  16.     ret=False
  17.  
  18.     print("\n\n=============== Countdown Timer ===============\n\n")
  19.  
  20.  
  21.     sec=int(input("Set your timer in sec: "))
  22.    
  23.     countdown(sec)
  24.  
  25.    
  26.     user_input=input("\n\nTry Again? (Yes/No): ")
  27.     if user_input.lower()=='no':
  28.         print("Exit program.")
  29.         break
  30.  
  31.     elif user_input.lower()=='yes':
  32.         ret=True
  33.  
  34.     else:
  35.         print("Wrong input.")
  36.         ret=True
  37.  
  38.  
  39.     if ret:
  40.         continue

In the provided code, we simply enclosed the code with a while loop to allow for continuous execution of the program. We will create a method that will set the timer based on the input you provide. You just need to call the method in order to display the timer.

Output:

The How to Create a Countdown Timer in Python source code that I provide can be download below. Please kindly click the download button.

There you have it we successfully created How to Create a Countdown Timer in Python. I hope that this simple tutorial help you to what you are looking for. For more updates and tutorials just kindly visit this site. Enjoy Coding!

More Tutorials for Python Language

Python Tutorials

Add new comment