Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

print() functions executes only after for loop is finished in python 3 [duplicate]

I want to display a series numbers in the same line using a for loop, this is what I did:

for i in range(10):
    sleep(1)
    print(i, end=" ")

This is supposed to print the numbers (0, 1, 2, ..., 10) one after another with each iteration of the for loop, instead the program waits until the loop has finished and then prints all the numbers at once.

I don't understand why this is happening, does any one have any idea what causes this behavior and thanks?

like image 790
Toni Joe Avatar asked May 19 '26 08:05

Toni Joe


1 Answers

Your stdout is line buffered; this means that it won't show text until a newline is encountered. You need to explicitly flush the buffer:

for i in range(10):
    sleep(1)
    print(i, end=" ", flush=True)

From the print() function documentation:

Whether output is buffered is usually determined by file, but if the flush keyword argument is true, the stream is forcibly flushed.

And from sys.stdout:

When interactive, standard streams are line-buffered.

like image 67
Martijn Pieters Avatar answered May 21 '26 16:05

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!