Local Variables in Python
Local variables in Python are the variables that are defined and can be used inside a function block only. In simpler words, the score (lifetime) of local variables is limited only to that function in which it was created.
Local variables become out-of-reach when control gets transferred out of the function and hence are not accessible outside the function.
Let’s check the sample code :
Program : To check the implementation of local variables
def fun1(a, b):
add = a + b # here, 'add' is a local variable
print(add) # prints '15'
# function fun1 invoked
fun1(5, 10)
# trying to access the local variable created under fun1()
print(add) # results in NameError
O/P:
15
Traceback (most recent call last):
File “”, line 7, in
NameError: name ‘add’ is not defined
NameError in Python : A NameError is raised when we try to access a variable or a function name that does not exists.
Global Keyword in Python
Global Variable in Python is a variable that can be accessed from anywhere in the program. Global variables have larger scope or lifetime.
This is achieved with the help of global keyword in Python. This keyword is added just before variable name to make it accessible over the program.
Syntax
global a
Here, ‘a’ is the global variable.
Global Keyword in Python comes into picture when global variable and the local variable have same name. In such cases, function generally ignores the global variable and refers to the local variable, To overcome this, we use global keyword.
Let’s understand this with a case-study
CASE 1 : No use of global keyword
num1 = 40 # more of a global variable
def fun():
num1 = 30 # defining local variable with same name as global
num1 += 1 # incrementing it by 1
print(num1) # print 31, considering 30 + 1
fun()
O/P : 31
CASE 2 : With use of global keyword
num1 = 40 # more of a global variable
def fun():
global num1 # accessing global value of num1
num1 += 1 # incrementing it by 1
print(num1) # print 41, considering 40 + 1
fun()
O/P : 41
Ever wondered, what if we want to assign this global variable to a local variable inside a function, we use globals() function.
globals() function in Python
globals() function in Python is a built-in function which returns the complete list of current global variables in the form of dictionary.
Syntax
globals()['a']
Here, ‘a’ is the global variable.
Program : To check the implementation of globals() function in Python
num1 = 40 # more of a global variable
def fun():
num1 = 20 # local variable num1
print("Local Variable num1 : ", num1)
duplicate = globals()['num1']
print("Cloning value of global variable : ", duplicate)
fun()
print("Value of num1 outside function :", num1)
O/P
Local Variable num1 : 20
Cloning value of global variable : 40
Value of num1 outside function : 40
That’s all about local and global variables in Python.