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
def ad(a,b):
sm=a+b
print(sm)
ad(10,20)
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
def ad(a,b):
sm=a+b
print(sm)
ad(10,20)
print(sm)
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
val=10
def ad(a,b):
print(a+b+val)
ad(10,30)
print(val)
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/