Scope of variables
Variables can only reach the area in which they are defined, which is called scope. Think of it as the area of code where variables can be used.
or
A scope of a variable is a region from where it can be accessed.
Python supports global variables (usable in the entire program) and local variables.
Local Scope
A variable created inside a function belongs to the local scope of that function, and can only be used inside that function.
def myfun(): a=15 //local variable print(a) b=95 // global variable print(b) myfun() print(b)
In the above example variable “a” is declared inside a function. so it is a local variable and its scope is local to the function in which it is declared.
Global Scope
A variable created in the main body of the Python code is a global variable and belongs to the global scope. Global variables are available from within any scope, global and local.
Example 1:
def myfun(): a=15 //local variable print(a) b=95 // global variable print(b) myfun() print(b)
In the above example variable “b” is declared outside a function. so it is a global variable and its scope is global i.e. it is present in full program (i.e. all the functions of the program).