Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display a countdown on a single line in the console?

I need a countdown timer in python but without skipping line.

from time import sleep

for c in range (4,0,-1):
   print(c)
   sleep(1)

this code makes the countdown by jumping the lines ex:

print('3')
print('2')
print('1')

I need that in the same line show first 3, then 2, last 1. ex:

print('3,' + sleep(1) + '2,' + sleep(1) + '1.')
like image 979
Sóstenes Melo Avatar asked Mar 07 '23 14:03

Sóstenes Melo


1 Answers

If you want delete previous number in console, you can do like

from time import sleep
import os

for i in range(4, 0, -1):
    os.system("cls")
    print(i)
    sleep(1)

this.

or you can use end parameter in print function.

from time import sleep

for i in range(4, 0, -1):
    print(i, end = '\r')
    sleep(1)

like this.

like image 166
SaGwa Avatar answered Mar 16 '23 05:03

SaGwa