Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel


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!!!


>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading