How To Create A Countdown In Python

In this tutorial, we will see how to create a countdown in python. The code will take input from the user regarding the length of the countdown in seconds. After that, a countdown will begin on the screen of the format ‘minutes:seconds’. We will be using the time module for this program.

time.sleep()

We will be using the time module. Then we will be using the sleep() function. To use this function we will first import the time module into our code. time.sleep(n) function makes the code wait for ‘n’ seconds. So, for this countdown we will be using time.sleep(1) as we want the code to wait for 1 second in between two successive prints.

import time

Let the Countdown begin with python

  1. We will import the time module.
  2. We will then ask the user to input the length of countdown in seconds.
  3. This value is sent as a parameter t’ to the user- defined function countdown(). Any variable read using input function is a string. So, we type convert this parameter to ‘int’ as it is of string type.
  4. In this function a while loop runs till time becomes 0.
  5. We then use divmod() to calculate the number of minutes and seconds. You can read more about it here.
  6. Then we will print the minutes and seconds on the screen using the variable timeformat.
  7. Using end = ‘\r’ we force the cursor to go back to the start of the screen (carriage return), so that the next line printed will overwrite the previous one.
  8. time.sleep() is used to make the the code wait for one sec.
  9. We then decrement time so that the while loop can converge.
  10. After the completion of the loop we will print “Blast Off!!!” to signify the end of the countdown.
import time

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('Blast Off!!!')

t = input("Enter the time in seconds: ") 
countdown(int(t))

Output:

countdown in python
Image reference: https://stackoverflow.com/questions/25189554/countdown-clock-0105#

So, here it is.  A very simple and fun program to create a Countdown in Python.

Also read,

Create Hangman game in pytho

Create A Stopwatch In Python





Leave a Reply

Your email address will not be published. Required fields are marked *