>>> import sys
>>> print(sys.version)
2.4.4
>>> b = 11
>>> def foo2():
... a = b
... print a, b
...
>>> foo2()
11 11
>>> def foo3():
... a = b
... b = 12
... print a, b
...
>>> foo3()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in foo3
UnboundLocalError: local variable 'b' referenced before assignment
>>> def foo4():
... global b
... a = b
... b = 12
... print a, b
...
>>> foo4()
11 12
Question> In foo3, why you can access global variable without declaring it but you still cannot modify it.
Without a
globaldeclaration, the Python compiler scans the whole code of each function to see which variables are assigned to within the function code. Infoo3(), you assign to bothaandbso therefore they are both treated as local variables within the function.When the method code executes, at the point where you do
a = b,bdoes not have a value yet (because you have not assigned anything to it). Therefore, you get anUnboundLocalError.This is done so that the use of a variable within a function always refers to the same location, even if nothing has been assigned to it yet.