!! Scope When you type a __name__ its definition (and therefore its meaning and usage) as used by the Python interpreter depends on where it is defined. To determine where a name is defined, Python depends on In Python, a variable is only available from inside the region it is created. This is called __scope__. There are five different scopes: * __local scope__: names defined inside a function (or lambda) * __enclosing scope__: names in the local scope of enclosing functions (nested functions) * __function inside function__: * __global scope__: names defined at the top level of a module (or declared global with the global keyword) * __built-in__: reserved names preassigned by Python (e.g., {{import}}, {{def}}, {{for}}) [{TableOfContents}] ---- !! Local Scope These are names defined inside a function or method. %%filename local_scope.py %% %%python {{{ # example of local scope def local_example(): # define a variable 'x' whose scope is local to the function x = "I'm local" print(x) # if we call local_example() the result will print "I'm local". local_example() # the following would result in an error, as x is not defined outside the function print(x) }}} %% !! Enclosing Scope These are names defined in the local scope of an enclosing function. %%filename enclosing_scope.py %% %%python {{{ # example of enclosing scope def outer(): # we define a variable 'x' within the scope of the outer() function x = "I'm in the enclosing scope" def inner(): print(x) # accesses x from enclosing function # if the outer() function is called, inner() is called too inner() # we call the outer() function outer() }}} %%