3

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?

Toni Joe
  • 7,715
  • 12
  • 50
  • 69

1 Answers1

11

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343