Lost in code
Lost in code

Reputation: 313

Why is my python sleep function not working correctly?

I'm trying to make a program that prints words one letter at a time, but with a pause in between each letter. I found a function called sleep that should help. I'm using the sleep function for that, but it first waits, then prints the text, instead of how I want it. Here's my code:

from time import sleep

firstline = "Hello!"
for i in range(len(firstline)):
    print(firstline[i], end = "")
    sleep(1)

It should print each letter of Hello! with a 1 second pause in between the letters. But it just waits six seconds, then prints it all at once. I'm new to python, so if you find a bug in my code, please tell me. Thanks.

Upvotes: 0

Views: 494

Answers (1)

Mark Tolonen
Mark Tolonen

Reputation: 178189

The standard output stream is buffered and flushes on newline. You need an explicit flush if not outputting a newline.

Also consider whenever you see the for x in range(len(y)): pattern that for x in y: is all that is needed.

from time import sleep

firstline = "Hello!"
for letter in firstline:
    print(letter, end = "", flush=True)
    sleep(1)

Upvotes: 5

Related Questions