Hour 14: Uderstanding Scope and Storage Classes

Example 14.1, Page No 225

In [11]:
i=32
print "Within the outer block: i=%d" % i
#There are no direct blocks in Python. We will do it in different way
print "Within the inner block"
def fu():
    j = 10
    for i in range(11):
        print "i=", i, "j=",j
        j -= 1
fu()
print "Within the outer block: i=%d" % i
Within the outer block: i=32
Within the inner block
i= 0 j= 10
i= 1 j= 9
i= 2 j= 8
i= 3 j= 7
i= 4 j= 6
i= 5 j= 5
i= 6 j= 4
i= 7 j= 3
i= 8 j= 2
i= 9 j= 1
i= 10 j= 0
Within the outer block: i=32

Example 14.2, Page No 227

In [17]:
#Python does'nt provide block creating facility like using just {} with out any name hence i have implemented in this way

def function_1():
    x = 1234
    y = 1.234567
    print "From fuction_1:"
    print "x=", x, ", y=", y

x = 4321
function_1()
print "Within the main block:" 
print "x=%d, y=%f" %(x, y)

y = 7.654321
function_1()
print "Within the nested block:"
print "x=%d, y=%f" %(x, y)
    
From fuction_1:
x= 1234 , y= 1.234567
Within the main block:
x=4321, y=7.654321
From fuction_1:
x= 1234 , y= 1.234567
Within the nested block:
x=4321, y=7.654321

Example 14.3, Page No 230

In [11]:
counter =0
def add_two(x,y):
    global counter
    counter = counter+1
    print "This is the function call of %d," % counter
    return (x+y)
j = 5
for i in range(5):
    print "The addition of "+ str(i) +" and "+str(j)+" is "+str(add_two(i,j))
    j=j-1
This is the function call of 1,
The addition of 0 and 5 is 5
This is the function call of 2,
The addition of 1 and 4 is 5
This is the function call of 3,
The addition of 2 and 3 is 5
This is the function call of 4,
The addition of 3 and 2 is 5
This is the function call of 5,
The addition of 4 and 1 is 5