Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 458
Aloysia de Argenteuil Avatar asked Aug 26 '16 10:08

Aloysia de Argenteuil


People also ask

How do you print a value on the same line in a loop?

To print in a for loop in one line: Use a for loop to iterate over the sequence. Set the end argument of the print() function to an empty string. The items in the sequence will get printed on the same line.

How do I print two statements on the same line in Python?

To print multiple expressions to the same line, you can end the print statement in Python 2 with a comma ( , ). You can set the end argument to a whitespace character string to print to the same line in Python 3.

How do you print on the same line in Python without space?

To print without a new line in Python 3 add an extra argument to your print function telling the program that you don't want your next string to be on a new line. Here's an example: print("Hello there!", end = '') The next print function will be on the same line.


1 Answers

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

like image 120
Martijn Pieters Avatar answered Nov 14 '22 23:11

Martijn Pieters