Local and Global Variables in Python
When we declare a variable inside a function , it becomes a
local variable . A local variable is a variable whose scope is limited only to
that function where it has been created .
This means that the local variable value is available only
within that function and not outside that function .
Example
variable 'a' is declared inside the myfunction() function
and hence this is available within that function .
Once the code logic comes out of the scope of the function , the
variable in use over here that is 'a' is removed from the memory and it is no
more available in the memory .
Following is an example of a code, which uses a local variable
within a function , and when the local variable defined within a function is
tried to be accessed outside the scope of the function , an error is produced .
# local variable within a function
def
myfunction():
a = 1
# here , a is a local variable
a = a + 1 #
increment local variable value
print(a)
myfunction()
print(a) # error , not available
One can observe from the last statement that is print(a) we are displaying the value of
variable 'a' outside the scope of the function . This statement raises an error
with a message name 'a' not defined .
When a variable is declared above a function, the value becomes
a global variable. Such variables are available to all the functions which are
written after it, If such a variable is declared above a function, then such a
variable becomes a global variable. Such type of variables is available to all
the functions which are written after it. One can consider a sample piece of
code for understanding the same :
Example
# global variable example
var_a = 1 #
this is a global variable
def somefunction():
var_b = 2 #
this is a local variable
print(' variable a = ',var_a
# call to display global var
val
print(' variable b = ,'var_b) # call to display local variable's
somefunction()
#
call to the function
print(var_a) # the value is accessible outside function
print(var_b) # the value is not accessible outside function
rather its value was only obtained when the call to
function
'somefunction' got executed.