Skip to content
Advertisement

How to fix double output in python

How do i fix a bug where Hello world! is printed twice?

The output:

{clear}Hello World! {clear}{clear}Hello World! The terminal is cleared [Finished in 3.4s]

The code:

messages = []

def render():
    os.system("cls")
    for msg in messages:
        print(msg)

def msg(message:str):
    messages.append(message)
    render()
def clear():
    messages = []
    os.system("cls")

msg("Hello world!")
time.sleep(3)
clear()
msg("The terminal is cleared")

Advertisement

Answer

clear does not clear the global list messages; it creates a new local variable that is assigned an empty list before going away when clear returns. Either use global

def clear():
    global messages
    messages = []
    os.system('cls')

or use the clear method:

def clear():
    messages.clear()
    os.system('cls')
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement