Problem using time and print

2

The following code does not work as expected using Python 3.5

import time
for letter in "Hello World!!":
    print(letter, end="")
    time.sleep(.5)

Instead of printing each letter with a short time interval, it just pauses, and at the end I print all the text. I would like you to help me

    
asked by anonymous 08.07.2017 / 20:53

1 answer

2

The problem is that end="" caches writing from memory and only writes content at the end of all writes. This can be bypassed by starting python with python -u or setting the environment variable PYTHONUNBUFFERED .

A simpler alternative is to force output to the console using the flush parameter in print:

import time
for letter in "Hello World!!":
    print(letter, end="", flush=True) #flush agora forçado aqui
    time.sleep(.5)

The solution of flush=True only works in version 3.3 up

    
09.07.2017 / 01:59