Watch Me Code 3: Understanding Function Variable Scope


In [26]:
def area_incorrect():
    area = length * width # these are in the global scope!!!!
    return area

In [27]:
## This is a bad idea

length = 10
width = 5
area = area_incorrect()
print ("length=",length, "width=",width, "area=",area)


length= 10 width= 5 area= 50

In [28]:
## Always pass in arguments from the global scope!

def area_correct(length, width):
    area = length * width # these are local copies from the global scope...
    length = 0 
    width = 0 # what happens here, stays here!
    return area

In [29]:
# in the global scope
length = 5
width = 10
area = area_correct(length,width)
print ("length=",length, "width=",width, "area=",area)


length= 5 width= 10 area= 50

In [ ]: