1
import time

def exitpro(t):
    a=0    
    while t>=0:
        timer="Loading "+"."*((a%3)+1)
        print(timer,end='\r')
        
        time.sleep(1)
        t-=1
        a+=1

    t=int(input("enter time in seconds "))
    exitpro(int(t))

I am doing this on jupyter notebook. I want to print something like "loading." then after one sec "loading.." then "loading..." then again "loading.". But when I run this it prints till 3 dots and then prints the loading with one dot overlapping the loading with 3 dots, so it looks like the program is stuck at loading with 3 dots. Basically, it does not clear the above line, rather prints over it. Please help.

Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70

1 Answers1

1

\r doesn't clear the line. It simply moves the cursor to the start of the line. You need to actually clear the line, either by explicitly clearing it before you write Loading., or by writing Loading. (notice the extra spaces after the period) to overwrite the extra periods.

import time

def exitpro(t):
    a=0    
    while t>=0:
        dotcount = (a % 3) + 1
        timer="Loading" + "." * dotcount + " " * (3 - dotcount)
        print(timer, end='\r', flush=True)
        time.sleep(1)
        t-=1
        a+=1

t=int(input("enter time in seconds "))
exitpro(t)

flush=True forces the output to print immediately instead of waiting to be buffered.

Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70