Sunday, August 2, 2020

Scope of Variables in function

Scope of variable:

Scope of a variable means the part of the program where the variable is accessible. Based on this the variable can have two scopes 1. Global Scope 2. Local Scope

Local variable:

A variable(identifier) defined inside the function will have a Local Scope i.e the identifier is accessible/used inside the function body only

In [1]:
def ad(a,b):
    sm=a+b
    print(sm)
ad(10,20)
30

now in the above code the variable sm is used inside the body of ad without any error but if we use it outside, we will get an error

In [2]:
def ad(a,b):
    sm=a+b
    print(sm)
ad(10,20)
print(sm)
30
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-2-ea525e1d6d50> in <module>
      3     print(sm)
      4 ad(10,20)
----> 5 print(sm)

NameError: name 'sm' is not defined

here in line 5, we get an error as sm is not accesible here as sm has Local Scope. Hence sm is a Local Variable

Global Variable:

Variable(identifier) defined outside the function i.e. on the top level(__main__) will have a Global Scope i.e. the variable can be used at any part of the program

In [3]:
val=10
def ad(a,b):
    print(a+b+val)
ad(10,30)
print(val)
50
10

in the above code, we can see that the variable val can be used both inside as well as outside the function without getting an error as val is a Global Variable and has Global Scope

Note:

if the same identifier exists inside as well as outside the function with different values, then Name resolution is used

Parameters & Arguments are local to the function:

parameters and arguments have local scope i.e. they can be used inside the function only and can not be used from outside(but if we return them then we can use). once the function execution is over, the variable, parameters get destoyed and removed from the memory, hence they can't be used outside

References:

  • Computer Science with python by sumita arora
  • http://openbookproject.net/thinkcs/python/english3e/
Share: