Problem with printing and sleeping in for loop with end key word argument

Question:

When I write the following code into python file/console:

import time, os

string = "what am I saying right now?"
for x in string:
    print(x)
    time.sleep(.1)

Output:

w
h
a
t
 
a
m
 
I
 
s
a
y
i
n
g
 
r
i
g
h
t
 
n
o
w
?

everything works as expected


However, when I add pass in anything to the end keyword argument it still works, but it does time.sleep(.1) methods before printing it out.

import time, os

string = "what am I saying right now?"
for x in string:
    print(x, end="")
    time.sleep(.1)
around 2.7 seconds later:

Output:

what am I saying right now?

There are a few issues with this:

  • The print statement is displayed after the whole loop is run (meaning the longer the string the longer it takes for the string to get printed out

  • There is no "cool" scrolling effect that is gotten from adding the sleep method after the print statement making it useless


if anyone knows why this happens and how I could mitigate this in the future that would be greatly appreciated.

Thanks in advance!!!


Asked By: Max Werner

||

Answers:

Try adding flush=True argument to print. Using empty char for end means there are no newlines in the output so line-buffered output will not write to terminal unless forced to by the flush

Answered By: delocalizer