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

I tried to print the result of the loop on the same line using python 3, and after reading Python: to print the loop on the same line, I managed to do this.

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

The problem is when I insert

 time.sleep(2) 

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

Here is the code:

 for x in range(1,10): time.sleep(2) print(x, end="") 

In this case, we expect 20 seconds (= 10 * 2), and only then are the numbers displayed. This is not what we expect.

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

+5
source share
1 answer

The output to stdout buffered in a line, which means that the buffer is not flushed until a new line is printed.

Explicitly flush the buffer every time you type:

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

Demo:

demo showing slowly added digits at 2 second intervals

+5
source

All Articles