Wednesday, 18 September 2013

accessing global frames in a user defined function

accessing global frames in a user defined function

a = 4
def foo(x):
a = 10
foo(2)
print(a)
#prints 4
The code above doesn't change a
a = 4
def foo(x):
return a + x
result = foo(10)
print(result)
#prints out 14
I don't quite understand how these two act differently. The second one,
the global variable obviously affects the local variable in foo. But if I
change a in the first one inside the foo, nothing happens to a in the
global frame. What is happening?

No comments:

Post a Comment