1

I was trying to make a code like this

def no(t=.001):
    print("N", end='')
    for i in range(1000):
        print('o', end='')
        time.sleep(t)
    print()

So that when I call no() I would print a long "Nooooo...", waiting some time between each 'o'. What happens instead is that the function halts, for the whole total time (1 second with the default argument), then prints the whole list. Is this intended? And if not how should I obtain my intended effect?

ABO
  • 170
  • 1
  • 1
  • 10

1 Answers1

2

What's happening here is that python is actually printing all the characters in exactly the same way that you intend - it writes the N, then an o per second to stdout. The issue is that the operating system does not display it because the file (stdout is a file) is not flushed. This typically automatically happens when \n is printed (by default, at the end of the printed string), but you'd overwritten that with end==''.

Luckily, print has an optional flush argument that you can use to force a flush. So you should be able to fix your behavior with this:

def no(t=.001):
    print("N", end='', flush=True)
    for i in range(1000):
        print('o', end='', flush=True)
        time.sleep(t)
    print()
inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241