0
import time

for i in range(20):
    time.sleep(1)
    print(i, end = ' ')

When I ran the above code in Python, I expected 0, 1, 2, ..., 19 to be printed every second. But actually 0 1 2 3 ... 19 was printed after 20 seconds. (I ran the script on the command prompt.)

I learned from the answer https://stackoverflow.com/a/107717/2091585 that this is caused by buffering and I can prevent this by adding

sys.stdout.flush()

after calling the print function.

On the other hand, if I ran it on Jupyter notebook, 0, 1, 2, and so on are printed every second as I expected.

Why doesn't the buffering occur in Jupyter notebook?

mkrieger1
  • 14,486
  • 4
  • 43
  • 54
user67275
  • 1,748
  • 4
  • 31
  • 51
  • 2
    Does this answer your question? [Python not printing output](https://stackoverflow.com/questions/55325145/python-not-printing-output) – snwflk Feb 17 '22 at 00:32

0 Answers0