0

I have a code in Python where I want it to print a pattern of dashes and points. The pattern generator works well, but I want it to print each new dash/point one at a time, not everything together. To accomplish so, I used the module time, and wrote this code:

import time


def inv(lista):
    inversa = []
    for ele in lista:
        if ele == '.':
            inversa.append('-')
        elif ele == '-':
            inversa.append('.')
    return inversa

patron = ['.', '-', '-', '.']

print('.--.', end = "")
bloques = 1

for bloques in range(6):
    newinv = inv(patron)
    
    for newele in newinv:
        print(newele, end = "")
        time.sleep(.5)
        patron.append(newele)

So basically what I want is for it to print one dash/point, wait .5 seconds, write the next one and so on. But when I run the code, it waits the whole time combined, and then prints the whole pattern at once in the console. Do you know what I did wrong? Thanks in advance!

  • I cannot reproduce the issue on Google Colab, so the results might depend on the way you are running your code. You could try passing `flush=True` to `print`, as described [here](https://stackoverflow.com/questions/230751/how-can-i-flush-the-output-of-the-print-function-unbuffer-python-output). – hilberts_drinking_problem Jan 08 '22 at 12:58
  • It will work as expected using a notebook, but in a shell the output will buffer. As mentioned by @hilberts_drinking_problem use `print(…, flush=True)` – mozway Jan 08 '22 at 13:01

0 Answers0