def f():
print(x)
def g():
print(x)
x = 1
x = 3
f()
x = 3
g()
It prints 3 when f is invoked, but the error message
UnboundLocalError: local variable 'x' referenced before assignmentis printed when the print statement in g is encountered. This happens because the assignment statement following the print statement causes x to be local to g. And because x is local to g, it has no value when the print statement is executed.
The above quote and code are from 《Introduction to Computation and Programming Using Python》 And here is my understanding through this explanation. Just wondering if this is valid:
The print statement in function f does not produce an error because it does not contain the name of x as a local variable, forcing the interpreter to search the stack frame with scope outside the definition of x and finding out that x binds to 3. Then use the value. While, in function g, there exists a local variable binds to number 1 after the print statement, the function already takes x as a local variable as x binds to some values in the function body. The interpreter does not search back to other stack frames with scope, hence the outer x bound will not be searched and used. Based on this, it has no value in x yet when the print statement is executed.