Unexpected UnboundLocalError:

Unexpected UnboundLocalError:

line 8, in coordinates
track = not track
UnboundLocalError: local variable ‘track’ referenced before assignment



6 track = TRUE
7 def coordinates :
8 track = not track

note line 8 is properly indented at input but shows not indented?
error occurs when mouse click calls coordinates

1 Like

In Python, variables that are used inside a function are known as local
variables. Before they are used, they must be assigned a value. A
variable that is used before it is assigned a value is assumed to be
defined outside that function; it is known as a global (or sometimes
nonlocal) variable. You cannot assign a value to such a global variable
inside a function without first indicating to Python that this is a
global variable, otherwise you will see an UnboundLocalError.

So, what you need here is the following:

track = True
def coordinates():
    global track  # <-- Add this
    track = not track

Note that I wrote True and not TRUE and that there are parentheses () following the name of the function, coordinates(), when I defined it. You likely had the same in your code (otherwise there would have been some syntax error and/or name error). In general, when asking questions, do not recopy by hand your code, but copy-paste it, adding extra indentation so that it shows properly.

1 Like

thanks! your explanation is crystal clear!

old, old C programmer since 1978 - new to python

tutorial and help pages said about scope that gobals, like in C, were in the scope of functions -
I did not see anywhere that globals must be imported into functions with the keyword global.
Probably a good idea to minimize name conflicts!

I did copy and paste code into the edit window with indents but it was displayed without indents in the window on the right of the edit window? How to paste code? - some forums have a means to quote code to make sure it is not garbled by the editor - how to quote code on discuss.python forum? I thought blockquote would do the trick, but no.

I use markdown syntax for code blocks: Creating and highlighting code blocks - GitHub Docs

only if you want to assign to it; if you just want to use the value of the global variable, it works just fine. assignments assume you’re creating a local variable unless a global declaration exists.