0

I am a newhand for python. Currently I want to do a Counters with closure in python. Why the following report error ' local variable 'a' referenced before assignment'

def createCounter():
    a = 0
    def counter():
        a =a + 1
        return a
    return counter

If I do :

def createCounter():
    L=[]
    def counter():
        L.append(1)
        sum=0
        for i in L:
            sum=sum+i 
        return sum
    return counter

And it works? why?

lululu
  • 31
  • 2
  • With `a = a + 1` you create a new local variable `a`. With `L.append(1)` you mutate an existing variable `L` from an outer scope. – Matthias Sep 02 '21 at 16:40

0 Answers0