How to create a Python count down from 100

In this tutorial, we will learn about how to create a Python count down from 100.

Simple and easy code:

import time
count = 100
while count > 0 :
    print(count)
    count=count-1
    time.sleep(1)

It will start the countdown from 100.

Also read: How to create a Stopwatch in Java

Count down with minute and second

For this purpose, we will import the time module.

import time

Initiate the value of a variable from 100.

count_down=100

We use for loop to iterate using the x variable starting from count_down value till its value becomes zero and decrement its value by -1 at the end of each iteration.

We assign the minutes and seconds lefts to variable sec and min as defined below.

Then, we print the minutes and seconds left using the time format. We end it by ‘\r’ so that output gets cleared and the new output gets generated in the same line.

Then we will use time.sleep() so that it waits for 1 second to generate the next output on the screen.

INPUT:

for x in range(count_down,0,-1):
    sec=x%60
    min=int(x/60)%60
    print(f'00:{min:02}:{sec:02}',end='\r')
    time.sleep(1)

EXPLANATION OF MATHEMATICS FORMULAS USED:

(For example:

x=100

seconds left will be 100%60 which gives 40 seconds.

minutes left will be (100/60)%60 which gives 1 minute.

Now, we decrement x value by 1:

x=99

seconds left will be 99%60 which gives 39 seconds.

minutes left will be (99/60)%60 which gives 1 minute.

This process goes until x becomes zero.)

 

When the countdown ends, we want to display a message-‘countdown ended’ which can be done as follows:

print('countdown ended')

Leave a Reply

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