Introduction
While working with functions, it is very much important to know about the scope of the variable.
In python, we have two types of variables
- Local Variables
- Global Variables
Local Variable
A variable that is declared inside the function is known as the local variable. Local variables can only be accessed from inside the function. We get the name error, if we try to access the local variable from outside the function.
def details():
#local variable
name = "Steve"
print("Name :", name)
def more_details():
print("Name :", name)
It works, as the variable name is defined in details function.
details()
It fails, as the variable name is local to details function and cannot be used outside that.
more_details()
Global Variable
A variable that is declared outside the function is known as the global variable. Global variables can be accessed throughout the program by all the functions.
#global variable
name = "John"
def details():
#local variable
name = "Steve"
print("Name :", name)
def more_details():
print("Name :", name)
It prints “Steve”, because we are locally overwriting name with “Steve”.
details()
As “name” variable is globally defined, so it works.
more_details()