5

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.')
martineau
  • 112,593
  • 23
  • 157
  • 280
Sóstenes Melo
  • 207
  • 1
  • 3
  • 12

1 Answers1

7

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.

SaGwa
  • 392
  • 1
  • 5
  • For this to work you *may* need to disable input buffering in python... – Shadow Nov 16 '17 at 02:42
  • If you change the range to span numbers of more than two digits, when you get to 9 you see '90' instead of '9' in the terminal. Setting flush=True on print() doesn't remedy this issue either. Why is this? – rafello Oct 11 '19 at 13:19
  • `sh: 1: cls: not found` – alper Dec 08 '21 at 02:05
  • @alper cls is clear command for Windows. you should use clear or method below. – SaGwa Dec 11 '21 at 08:46