The occurrence of an assignment to a variable within a function establishes the existence of a local variable of the specified name, unless that name was declared within the function as
global. That happens even before the expression to the right of the assignment operator is evaluated. The local scope of the name even applies to statements that occur prior to the first assignment to that name. Therefore, prior to evaluation of the expression to the right of the assignment, any reference to the name of the new variable refers to the local one.
x is not declared as
global in your
increase function, Python tries to create a local
x within that function based on the assignment statement. However, the assignment that you have provided also requires lookup of an
x, and it fails because the new local
x does not yet have a value within that function.
Check this out …
x = 7
x = 9
Traceback (most recent call last):
File "/Users/glennrichard/Documents/xf.py", line 6, in <module>
File "/Users/glennrichard/Documents/xf.py", line 3, in xf
UnboundLocalError: local variable 'x' referenced before assignment
See What are the rules for local and global variables in Python?
Edited several times for clarification of the explanation on December 24, 2017