For the following Python 2.7 code:
#!/usr/bin/python
def funcA():
print "funcA"
c = 0
def funcB():
c += 3
print "funcB", c
def funcC():
print "funcC", c
print "c", c
funcB()
c += 2
funcC()
c += 2
funcB()
c += 2
funcC()
print "end"
funcA()
I get the following error:
File "./a.py", line 9, in funcB
c += 3
UnboundLocalError: local variable 'c' referenced before assignment
But when I comment out the line c += 3 in funcB, I get the following output:
funcA
c 0
funcB 0
funcC 2
funcB 4
funcC 6
end
Isn't c being accessed in both cases of += in funcB and = in funcC? Why doesn't it throw error for one but not for the other?
I don't have a choice of making c a global variable and then declaring global c in funcB. Anyway, the point is not to get c incremented in funcB but why it's throwing error for funcB and not for funcC while both are accessing a variable that's either local or global.