Assigning a value to a name makes the name local if the name is not explicitly declared global.
a = 12 def foo(): a = 42 print a
If no name is assigned, it is global.
a = 12 def foo(): print a
In short, you need to explicitly declare a global name if you assign it. If you just read it, you can use it as you wish. However, if you ever assign this variable, it will be considered local in this function if you have not declared it global.
b = 5 def foo(): print b b = 7 foo() >>> ???
Since b is assigned in foo() and is not declared global, Python decides at compile time that b is a local name. Therefore, b is the local name in the entire function, including in the print statement before assignment.
Therefore, the print statement gives you an error, since the local name b not defined!
kindall
source share