5

So I'm having some trouble with Python. I have a code that is:

import time

def printChat(string, sleepTime):
    for a in string:
        print (a, end="")
        time.sleep(sleepTime)
    print()

When I do printChat("Hello", 0.1) it should print a letter and wait 0.1 seconds and then print the next one, but instead, it waits 0.5 seconds (as 'hello' is 5 characters long) and then prints hello all of a sudden. Any idea why that is?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
WhoKnows
  • 73
  • 3

1 Answers1

6

You should use:

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

Because console output is line-buffered.

llllllllll
  • 16,169
  • 4
  • 31
  • 54
  • Can you provide a source to the statement that console output is buffered? Isn't it stdout that's a buffered stream, no matter whether it goes to console or file? – phihag Mar 18 '18 at 17:11
  • @phihag If it's a file, then `'\n'` won't flush the buffer. Only console is line-buffered. – llllllllll Mar 18 '18 at 17:12
  • Thanks, it is now working fine. I'll accept the answer as soon as I can. – WhoKnows Mar 18 '18 at 17:15