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?