Monday, December 19, 2016

Scope Rules in Python


#Rule 1 - Scope Inheritance</u>

If a variable is not defined in a function, python tries to look the variable in global scope. It will throw error only if a variable is not defined in both local scope and global scope
In [8]:
def area_circle(radius):
    return pi * radius**2

pi = 3.14
print(area_circle(5))
78.5
In the above program, even though pi is not defined in area_circle function, it did not throw error, because it managed to get the pi value from global scope .
#Rule 2 - Scope Limits</u>
We can only use a variable from global scope in a function, but we cannot modify or reassign it inside a function.
In [11]:
a = 10
def prod_a():
    a = a*a 
    return a
print(prod_a())
---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
<ipython-input-11-c4e8f0ab0afb> in <module>()
      3     a = a*a # It will throw error, because we are trying to modify the global variable "a" inside a function.
      4     return a
----> 5 print(prod_a())

<ipython-input-11-c4e8f0ab0afb> in prod_a()
      1 a = 10
      2 def prod_a():
----> 3     a = a*a # It will throw error, because we are trying to modify the global variable "a" inside a function.
      4     return a
      5 print(prod_a())

UnboundLocalError: local variable 'a' referenced before assignment
In [12]:
a = 10
def prod_a():
    b = a*a
    return b
print(prod_a())
100
#Rule 3 - Global Variable :</u>
We can access modify global variable (declared as global) from both local and global scope
In [24]:
global b
b = 10
def prod_a():
    global b
    b = 2*b # It modifies the global variable b
    return b
print(prod_a())
print(b)
20
20
In [ ]:

No comments :

Post a Comment