It is important to understand the scoping rules of variables inside functions. Each time a function executes, a new local namespace is created. This represents a local environment that contains the names of the parameters and variables that are assigned by the function. To resolve a namespace when a function is called, the Python interpreter first searches the local namespace (that is, the function itself) and if no match is found, it searches the global namespace. This global namespace is the module in which the function was defined. If the name is still not found, it searches the built-in namespace. Finally, if this fails then the interpreter raises a NameError exception. Consider the following code:
a=10; b=20
def my_function():
global a
a=11; b=21
my_function()
print(a) #prints 11
print(b) #prints 20
If you want to change selection, open document below and click on "Move attachment"
pdf
owner:
kkhosravi - (no access) - PYTHON_DATA_STRUCTURES_AND_ALGORITHMS.pdf, p27
Summary
status | not read | | reprioritisations | |
---|
last reprioritisation on | | | suggested re-reading day | |
---|
started reading on | | | finished reading on | |
---|
Details