End parameter in print() function

Question:

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?

Asked By: user18100428

||

Answers:

The r is a carriage return character, so instead of ending with a newline (n) (which would cause each print statement to issue on a new line), each print statement overwrites the previous one.

Answered By: cteljr

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.

Answered By: The_spider
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.