Search code examples
pythontimer

End parameter in print() function


I'm looking at this code:

import time   
def countdown(t):
    while t:
        mins, secs = divmod(t,60)
        timer = '{:02d}:{:02d}'.format(mins,secs)
        print(timer, end='\r')
        time.sleep(1)
        t-=1
    print("Timer is completed")
t=input('Enter the time in seconds: ')
countdown(int(t))

In the print call (on line 6) is end='\r'. What does this indicate or do in the program?


Solution

  • In python, \rin a string stands for the carriage return character. It does reset the position of the cursor to the start of the current line. The end argument in the print function is the string that is printed after the given text. By default, this is \n, a newline character.

    In the timer we do want that the new time overwrites the previous one, not that the new time is printed after the previous one. Thus, the end argument of the print function is set to \r, such that the cursor is moved to the back of the line. This makes thet the new time is printed over the new one.