Problem using time and print

Asked

Viewed 70 times

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 interval of time, it just pauses, and at the end I printed out all the text. I would like you to help me

  • I pasted your code on repl it. and the execution took place exactly as you wish, a letter every half second.

  • @Sidon really worked, but on my laptop it doesn’t work, don’t know if the version of something to see

  • @Sidon so much that using the python site itself shell (python Anywhere), this code presented this problem

1 answer

2


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

A simpler alternative is to force the output to the console using the flush parameter in the 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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.