0

I have a loop in python that is sleeping 0.1 seconds every iteration. It is sequentially printing out a string to the console. I want it to add a character every iteration, But the problem is that it waits until the loop is finished to display the text. This only happens when I have the ", end='' " bit at the end of the print call.

import time def speak(text): i = 0 for i in range(0, len(text) + 1): print(text[i], end='') i += 1 time.sleep(0.1) speak("Test 123. Can you see me?") 
2
  • show your code please Commented Jul 15, 2016 at 0:39
  • Add the flush parameter to the print function to get it to print immediately: print(text[i], end='', flush=True) Commented Jul 15, 2016 at 0:42

1 Answer 1

0

As the comments say, you need flush=True in your call to print(...).

Also, your loop goes one character off the end of the string (causing an exception), and it would be nice to print a newline at the end of the text. Here's a fixed up version that works on my machine:

import time def speak(text): for c in text + '\n': print(c, end='', flush=True) time.sleep(0.1) speak("Test 123. Can you see me?") 
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I'm kinda new to python. I love how fast this community responds to questions!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.