The purpose of my question is to strengthen my knowledge base with Python and get a better picture of it, which includes knowing its faults and surprises. To keep things sp
If you assign to a variable inside a function, Python assumes that the variable is defined inside that function:
>>> x = 1
>>> def increase_x():
... x += 1
...
>>> increase_x()
Traceback (most recent call last):
File "", line 1, in
File "", line 2, in increase_x
UnboundLocalError: local variable 'x' referenced before assignment
Use global x
(or nonlocal x
in Python 3) to declare you want to set a variable defined outside your function.