I'm misunderstanding with closures and the code is
Code 1
def test_int():
a = 1
def plus():
print(a)
a += 1
plus()
test_int()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 6, in test_int
File "<stdin>", line 4, in plus
UnboundLocalError: local variable 'a' referenced before assignment
Code2
def test_int():
a = 1
def plus():
print(a)
print(locals())
plus()
test_int()
1
{'a': 1}
- Why is code2 correct but code1 is wrong? However, when a is an array, code3 is correct.
Code 3
def test_arr():
a = [0]
def plus():
a[0]+=1
print(a)
plus()
test_arr()
[1]
- What is the difference between int and array when define a free variable?