Python: time.sleep functions unexpectedly?
Question: I'm trying to make a simple function that will type out a string letter by
letter, such as in a game, where text scrolls.

Here's what my code looks like:

    
    
    import time
    
    def ScrollingText(s):
         s=str(s)
         for letter in s:
              print(letter, end="")
              time.sleep(.05)
         print("")    # newline at the end
    if __name__=='__main__':
         ScrollingText("Hello World!")
    

However when I run, it waits, then dumps out the whole string at once. I'm new
to python (and this forum as well) so if anyone can point me in the right
direction and show me what I'm missing here in time.sleep I'd greatly
appreciate it. Thanks!


Answer: As you do not have a newline in your string, python will buffer it. You have
to explicitly flush the output after each character like this:

    
    
    import sys
    import time
    
    def ScrollingText(s):
         s=str(s)
         for letter in s:
              print(letter, end="")
              sys.stdout.flush()
              time.sleep(.05)
         print("")     # newline at the end
    

For better performance, I/O is usually buffered, that is, python will collect
the data you print until it can send it out as a large block (this also goes
for file I/O by the way). By calling
[flush()](http://docs.python.org/2/library/stdtypes.html#file.flush) on
sys.stdout (which is the file object where print writes to by default), you
force python to send your data to the operating system (and that will send it
to your terminal).

