Python variables
In python, we have two types of variables based on its scope
- Local variables
- Global variables
Local variables
When we declare a variable inside a Python function, it becomes a local variable . A local variable is a variable whose scope is limited only to that function where it is created. That means the local variable value is available only in that function and not outside of that function . In the following example, the variable 'a' is declared inside myfunction() and hence it is available inside that function. Once we come out of the function, the variable 'a' is removed from memory and it is not available. Consider the following code:
def myfunction():
a=1
a+=1
print(a)
myfunction()
print(a)
Global variables
When a variable is declared above a Python function, it becomes global variable . Such variables are available to all the functions which are written after it. Consider the following code:
a=1
def myfunction():
b=2
print('a=', a)
print('b=', b)
myfunction()
print(a)
print(b) #error,
not available Whereas the scope of the local variable is limited only to the function where it is declared, the scope of the global variable is the entire program body written below it.
Sometimes, the global variable and the local variable may have the same name. In that case, the function, by default, refers to the local variable and ignores the global variable. So, the global variable is not accessible inside the function but outside of it, it is accessible.
variables examples:
a=1
def myfunction():
a=2
print('a=', a) #display local var
myfunction()
print('a=', a) #display global var
When the programmer wants to use the global variable inside a function, he can use the keyword 'global' before the variable in the beginning of the function body as:
global a
In this way, the global variable is made available to the function and the programmer can work with it as he wishes. In the following program, we are showing how to work with a global variable inside a function.
A Python program to access global variable inside a function and modify it.
a=1
def myfunction():
global a
print('global a=', a)
a=2 #modify global var value
print('modifed a=', a) #display new value
myfunction()
print('global a=', a)