I noted all of the same issues that @TimothyChen mentioned. I'd like to explain the error you're asking about, which is:
UnboundLocalError: local variable 'v' referenced before assignment
That happens here:
v = 1
def secondary()
v += 1
The issue here is due to a behavior that is unique to Python, and a little strange (please excuse that I changed the name variable
to v
to avoid confusion)...
If there is a global variable declared named v
, and then you only read from a variable named v
inside a function, Python declares that you are reading from the global variable named v
.
If there is a global variable declared named v
, and then you write to a variable named v
inside a function, Python says that that's a different variable local to the function unless you first say global v
in that function, after which point v
refers to the global variable.
So the case of your function secondary()
, you are A) writing to v
in the function, and B) you don't say global v
anywhere in the function. So Python says that inside that function, v
is a unique variable local to that function. But if v
is local to the function, and your first reference to the variable in that function is:
v += 1
then v
hasn't been assigned a value prior to this point. Since this line of code first reads from v
, and then writes a new value back to it, you get the error you're seeing because of the attempt to read from a variable that hasn't yet been assigned a value.
It seems pretty clear that what you need to do to fix this issue is to declare your secondary
function as follows:
def secondary()
global variable
variable += 1
return variable
The addition of global variable
tells Python that your reference to variable
is referring to the global variable with that name, even though you are writing to it.
I would suggest that in the future, you not name variables variable
. That can only lead to confusion.