5

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

time.sleep(2)

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):
    time.sleep(2)
    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.

Community
  • 1
  • 1
Aloysia de Argenteuil
  • 833
  • 2
  • 11
  • 27
  • Also see another duplicate [here](http://stackoverflow.com/questions/38411532/how-do-i-print-from-a-python-2-7-script-invoked-from-bash-within-pycharm/38411633). – TigerhawkT3 Aug 26 '16 at 11:09

1 Answers1

5

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)

Demo:

demonstration animation showing slowly-added digits at 2 second intervals

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