Tutorial by Examples

In Python, variables inside functions are considered local if and only if they appear in the left side of an assignment statement, or some other binding occurrence; otherwise such a binding is looked up in enclosing functions, up to the global scope. This is true even if the assignment statement is ...
If a name is bound inside a function, it is by default accessible only within the function: def foo(): a = 5 print(a) # ok print(a) # NameError: name 'a' is not defined Control flow constructs have no impact on the scope (with the exception of except), but accessing variable that w...
Python 3.x3.0 Python 3 added a new keyword called nonlocal. The nonlocal keyword adds a scope override to the inner scope. You can read all about it in PEP 3104. This is best illustrated with a couple of code examples. One of the most common examples is to create function that can increment: def c...
x = 5 x += 7 for x in iterable: pass Each of the above statements is a binding occurrence - x become bound to the object denoted by 5. If this statement appears inside a function, then x will be function-local by default. See the "Syntax" section for a list of binding statements. ...
Classes have a local scope during definition, but functions inside the class do not use that scope when looking up names. Because lambdas are functions, and comprehensions are implemented using function scope, this can lead to some surprising behavior. a = 'global' class Fred: a = 'class' ...
This command has several related yet distinct forms. del v If v is a variable, the command del v removes the variable from its scope. For example: x = 5 print(x) # out: 5 del x print(x) # NameError: name 'f' is not defined Note that del is a binding occurence, which means that unless expl...
What are local and global scope? All Python variabes which are accessible at some point in code are either in local scope or in global scope. The explanation is that local scope includes all variables defined in the current function and global scope includes variabled defined outside of the curren...

Page 1 of 1