Unbound Variables in Python
How Python figures out the scope of it's variables?
Consider the following example
Outputs
Python looks for take_sum
in local scope ie., inside main followed by global scope whereas,
Returns: UnboundLocalError: local variable 'take_sum' referenced before assignment
The function raises an exception because the compiler saw that the code could assign to take_sum
as a local variable, and so it makes all the references to take_sum
in the code be local. You can no longer look up the global variable take_sum
in the normal way once that determination has been made.
To understand how variable names are resolved read Python Namespaces
Last updated