0

I've searched on StackOverflow & elsewhere, but found no clues as to why this might be happening. However, I apologise in advance if this has been asked & answered previously & I've missed it.

I'm using Python 3.5.1 on OS X 10.11.3. When I run the (for example) following code in the IDLE shell...

 import time
 for i in range(0,101):
     print(i,end=' ')
     time.sleep(0.5)

...it does what I intended and prints 0 to 100 across the screen at the rate of 1 number+space every half second. But when i run the same code interactively in Terminal, there's a 50 second wait before the sequence 0 to 100 is printed across the screen all at the same time. Same behaviour occurs if code is run from a script, and also in a Windows environment.

I'm new to coding/Python, so please forgive any naivety, but please could anyone shed any light on this?

Thanks

Stuart

e55en
  • 1
  • 1

1 Answers1

0

You need to sys.stdout.flush() each time you're writing something to stdout and sleep.

from time import sleep
import sys

for i in range(1,100):
    print(i, end=' ')
    sys.stdout.flush()
    sleep(0.5)

This should work for you. More information: some other stack overflow question

Community
  • 1
  • 1
erhesto
  • 1,176
  • 7
  • 20
  • @e55en, if this answer helped you, consider marking it as accepted (at the top-left corner of the answer) :) – marcelm Mar 17 '16 at 16:11