ALevel 1 Python 26may SS
ALevel 1 Python 26may SS
O Level / A Level
Python uses the location of the name assignment or definition to associate it with a scope.
If a variable assigned value in the function, it has a local scope.
If a variable assigned value at the top level and outside all the functions, it has a global scope.
Types of namespace
1. Built-in Namespace It includes functions and exception names that are built-in in
the python.
2. Global Namespace It includes the names from the modules that are imported in
the code. It lasts till the end of program.
3 Local Namespace It includes the names defined in the function. It is created
when the function is called and ends when the value returned.
Built in Scope
Global Scope
Enclosing Scope
Local Scope
Example
#var1 is in the global namespace
var1 = 5
def ABC( ):
In this example, the var1 is declared in the global namespace because it is not enclosed
inside any function. So it is accessible everywhere in the script.
var2 is inside the ABC( ). So, it can be accessed only inside the ABC( ) and outside the
function, it no longer exists.
var3 also has a local scope, the function is nested and we can use var3 only inside XYZ( ).