-1

I am using a time.sleep function to have my strings printed letter by letter, and it works perfectly while running inside pycharm, yet when I save the program and run it directly, the function does not take effect

def welcome():
     greeting = random.choice(open_msg)
     for i in range(len(greeting)):
            print(greeting[i], end='')
            time.sleep(0.15)

This is an example of what the code looks like

rv.kvetch
  • 9,940
  • 3
  • 24
  • 53
Liam
  • 3
  • 1

3 Answers3

3

By default, Python's output is line-buffered. Therefore it won't print anything until you print a linefeed. To avoid this behavior, flush the output after each letter. Since Python 3.3, print() has an argument to do this. (For older versions, you need to sys.stdout.flush() after each print().)

print(greeting[i], end='', flush=True)

You can cause Python not to buffer by invoking it with the -u flag or by setting the environment variable PYTHONUNBUFFERED to any value. But these affect all output. It's better to use flush where you need it and leave other output buffered, because buffered is faster.

By the way, don't use range() when iterating over a string. Iterate over the string directly and you get the characters.

for c in greeting:
    print(c, end='', flush=True)
    # etc.
kindall
  • 178,883
  • 35
  • 278
  • 309
-1

Ides can take longer to execute, amplifying the time.sleep() function Maybe lengthen the time in the argument of time.sleep()

somedev
  • 1
  • 5
-3

It should be working. Perhaps you forgot one of your imports? If so, here is the code, it is written well.

import random
import time
open_msg = ['hello', 'finished', 'chicken']
def welcome():
    greeting = random.choice(open_msg)
    for i in range(len(greeting)):
        print(greeting[i], end='' )
        time.sleep(0.15)
welcome()
``
  • It only "should be working" (where "working" is understood to mean "printing one character at a time") if stdout is completely unbuffered. That's not true by default even when stdout is a TTY -- stdout is by default line-buffered when it goes to a TTY, or fully buffered (flushed in much larger blocks) otherwise. – Charles Duffy Oct 19 '21 at 02:07