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

Strange problem while using print's end argument in a loop

> python version 3.11.6
> os: Windows
> Idle: Visual studio code (Latest version)

My code looks something like this:

from time import sleep


x = [
"H",
"E",
"L",
"L",
"O"
]
for i in x:
    print(i, end="")
    sleep(.5)

when I run this expected output is:
H wait E wait L wait L wait O

but output is:
A long wait then all characters instantly.

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

But why?

I noticed when I don’t use end argument code works well.

""Additional info"":
also tried using sys.stdout.write() same problem.

>Solution :

When you use the end="" argument in the print function, it suppresses the newline character (\n) that print normally adds at the end of each print statement.

you can use flush=True argument in the print function, to solve this:

from time import sleep

x = [
    "H",
    "E",
    "L",
    "L",
    "O"
]

for i in x:
    print(i, end="", flush=True)
    sleep(.5)

As an alternative, you could achieve the same result by combining sys.stdout.write() and sys.stdout.flush():

import sys
from time import sleep

x = [
    "H",
    "E",
    "L",
    "L",
    "O"
]

for i in x:
    sys.stdout.write(i)
    sys.stdout.flush()  # Flush the output buffer
    sleep(.5)
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