how to stop the countdown loop

Question:

I am trying to create a countdown, how when it goes to 0 it will stop the loop and show a message

import time

countdown = 100

while True:

    display = " [ Countdown {:03d} ] ".format(countdown)

    print(display, end="r")

    time.sleep(2)

    countdown -= 1
Asked By: MThien

||

Answers:

you will need to add a setTimeout function. Example as shown below.

setTimeout(function(){
//Your code to be executed here
},3000);

Note: 3000 means 3seconds.

Answered By: Ola Min

A while loop is only executed while the expression after the while is true. In this case, that expression is True, which always evaluates to True.

Consider replacing this with something like countdown > 0 . Once this statement evaluates to False, the execution will exit the while loop and continue to code afterwards, where you can put your shown message.

Total code:

import time
countdown = 100
while countdown > 0: # While the condition is true, it will keep looping
    display = " [ Countdown {:03d} ] ".format(countdown)
    print(display, end="r")
    time.sleep(2)
    countdown -= 1
print('Countdown finished!') # Executed only once the loop is finished

If this answer helped, click the green checkmark to mark it as accepted.

Answered By: Mous

Replace the true value in the while loop that makes the condition for infinite loop
with

 import time

 countdown = 100

 while countdown >0:

   display = " [ Countdown {:03d} ] ".format(countdown)

   print(display, end="r")

   time. Sleep(2)

   countdown -= 1  
Answered By: Hope
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.