I'm trying to understand Python's
approach to variable scope. In this example, why is f() able to
alter the value of x, as perceived within
main(), but not the value of
n?
def
f(n, x):
n = 2
x.append(4)
print('In f():',
n, x)
def main():
n = 1
x =
[0,1,2,3]
print('Before:', n, x)
f(n, x)
print('After:
', n,
x)
main()
Output:
Before:
1 [0, 1, 2, 3]
In f(): 2 [0, 1, 2, 3, 4]
After: 1 [0, 1, 2, 3,
4]
No comments:
Post a Comment