Post Image

Python CLI Countdown

When creating CLI applications there are times where you want to be as interactive as possible and sometimes give a user a few seconds before executing a task as a warning or just for user experience. In this post I will demonstrate creating a countdown for a CLI application.

 

Design

In order to make this we will need to do the following.

  • Start with a number to count down from
  • Display text with that number
  • Wait 1 second
  • Decrement the number and repeat until we hit zero

 

Writing Code

First we will start by importing the libraries we need to use

from time import sleep

 

Next I will generate a list of numbers of 1 - 4, reverse the numbers so it is ordered from highest to lowest, and start a for loop

for x in reversed(range(1, 4)):

 

Inside the for loop I will display some text that shows the number and waits for 1 second before looping back over

for x in reversed(range(1, 4)):
    print(f'Starting in {x}', end='\r')
    sleep(1)

Notice here that when printing I end with the \r character which returns the cursor to the beginning of the line. I do this because I want each output to overwrite the previous line so we don't have a line for each number.

 

And lastly, outside of the for loop I display some text indicating that the program is continuing on

print('Starting!' + ' ' * 4)

Notice I append 4 spaces to the end, this is indicated by + ' ' * 4. I do this so that all of the text on the previous line of output inside of the loop is overwritten.

 

Complete Code

Below is the complete code that I built above.

from time import sleep

for x in reversed(range(1, 4)):
    print(f'Starting in {x}', end='\r')
    sleep(1)
print('Starting!' + ' ' * 4)

 

Running Code

Because this is interactive versus having each print statement on its own line it is hard to show on a static web page however when running this it should take 4 seconds to run, and you should be left with output that is similar to below.

$ python countdown.py
Starting!
$

 

 



Comments (0)
Leave a Comment