Aloysia de Argenteuil Aloysia de Argenteuil - 7 months ago 46
Python Question

Interpolate sleep() and print() in the same line inside a for loop using python 3

I was trying to print the result of a loop in the same line using python 3 and after reading Python: for loop - print on the same line I managed to do it.

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

The problem now is when I insert


before the print.
I would like to print the first character, wait two seconds, then the second, wait two more seconds, etc.

Here the code:

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

With that we wait 20 seconds (= 10*2) and only then the numbers are displayed. This is not what we expect.

What I should do to have the above expected behavior, namely wait 2 seconds, print first character, wait more 2 seconds, print second character, etc.


Output to stdout is line buffered, which means the buffer is not flushed until a newline is printed.

Explicitly flush the buffer each time you print:

print(x, end="", flush=True)


demonstration animation showing slowly-added digits at 2 second intervals