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?

0

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks this worked perfectly

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.