How to fix double output in python

Question:

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")
Asked By: The_SysKill

||

Answers:

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')
Answered By: chepner

in your "clear" routine you need to add "global messages". this will allow the "messages=[]" to work on the global variable instead of the local copy.

Answered By: user1200296
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.