Question:I made the two functions below in Python 3. The first function
test_listworks fine with the list
awithout error. I can modify the list element in that function.
However, the second funciton
test_intwill pop an error
local variable 'b' referenced before assignment. Why can’t I do this to the variable
b += 1is equivalent to
b = b.__iadd__(1); since the name
bgets bound by that statement (l.h.s.), the compiler infers that
bis a local variable; however, the r.h.s. expression contains the name
bas well and thus you get the error “local variable
'b'referenced before assignment” (the local name
bdoesn’t refer to anything at the time when the expression is evaluated).
a = 2on the other hand is equivalent to
a.__setitem__(0, 2)and thus involves no name binding.
If you wish to modify a global name binding within a function, you can use the keyword
global; there’s also the equivalent
nonlocalfor names contained in an outer, but not the global, scope.
If you have better answer, please add a comment about this, thank you!