Thursday, December 7, 2023
HomeSoftware EngineeringFind out how to create a Countdown Timer in Python

Find out how to create a Countdown Timer in Python


If you’ll want to depend down a selected period of time, say for instance, when a token is about to run out, then a countdown timer can be helpful.

Step 1 – Writing the Python code

Place the next Python code in a file known as countdowntimer.py

Possibility 1 – Textual content output

import time

def countdown(t):
  whereas t:
    minutes, secs = divmod(t, 60)
    timer = '{:02d}:{:02d}'.format(minutes, secs)
    print(timer, finish="r")
    time.sleep(1)
    t -= 1

  print('Countdown time has elapsed!!')

t = enter("Enter the time in seconds: ")

countdown(int(t))

Possibility 2 – Textual content and speech output

Right here we additionally invoke say which speaks out the textual content. That is solely native to some working methods.

Observe: In case you use MacOS, this may work out the field for you!

import time
import os

def countdown(t):
  whereas t:
    minutes, secs = divmod(t, 60)
    timer = '{:02d}:{:02d}'.format(minutes, secs)
    print(timer, finish="r")
    time.sleep(1)
    t -= 1

  txt = 'Countdown time has elapsed!!'
  print(txt)
  os.system('say "'+txt+'"')

t = enter("Enter the time in seconds: ")

countdown(int(t))

Step 2 – Calling the Python code

python3 <path_to_file>/countdowntimer.py

Elective Step 3 – Create an Alias

In case you use bash then do that:

echo "alias depend='python3 <path_to_file>/countdowntimer.py'" >> ~/.bash_profile

In case you use zsh then do that:

echo "alias depend='python3 <path_to_file>/countdowntimer.py'" >> ~/.zshrc

Now when you’ve reloaded the terminal session by doing one of many following:

  1. supply ~/.bash_profile
  2. supply ~/.zshrc
  3. Shut and reopen your terminal

You possibly can simply name depend and the appliance will begin.

What enter does it count on?

Whenever you first run the appliance, you possibly can specify the quantity of seconds to depend down from.

In case you enter 30, then it should depend down for 30 seconds.

In case you enter 3600 (60seconds x 60minutes), then it should depend down for an hour.

and so forth.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments