Scope in python follows this order:
Search the local scope
Search the scope of any enclosing functions
Search the global scope
Search the built-ins
(source)
Notice that if
and other looping/branching constructs are not listed - only classes, functions, and modules provide scope in Python, so anything declared in an if
block has the same scope as anything decleared outside the block. Variables aren't checked at compile time, which is why other languages throw an exception. In python, so long as the variable exists at the time you require it, no exception will be thrown.