Bug with python mode

Hi, @CodeMasterX,

It is important to note that there are two variables named txt in your program, one being global, and the other one local to the draw function. Because the draw function contains at least one assignment to txt, and the variable was not explicitly declared global within the function, that name refers to a local variable by that name, wherever used inside the function, even if none of those assignment statements ever gets executed. Of course, your else block does guarantee that at least one of the assignments will get executed, but that has no bearing on the scope of that variable.

If you do display the value of the global variable, txt, you will find that it is distinct from the local variable by that name. To demonstrate that, add this function to your code, making sure that its header is not indented, and call it from within the draw function:

def print_the_global_txt():
    # txt is not assigned anything within this function, 
    # therefore, we are accessing the global variable, txt
    print(txt)

You can add a call to the function as the final line in the draw function, indented directly under the call to text, as shown here:

    text(txt,mouseX,mouseY)
    print_the_global_txt()

Alternatively, you can place the call within one of the conditional blocks.

Regardless of what happens inside the draw function, the print_the_global_txt function will always display 1 in the console when it is called, because it is accessing the global variable.

See official documentation at Python.org: What are the rules for local and global variables in Python?. It states:

In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared as global.

3 Likes