Title: Using closures to return a counter function that returns an increasing integer each time I call it

def createCounter() :
    i = 0
    def counter() :
        i+=1
        return i 
    return counter
Copy the code

But an error occurred

Traceback (most recent call last):
  File "main.py", line 12, in <module>
    print(counterA(), counterA(), counterA(), counterA(), counterA()) Number 1, 2, 3, 4, 5
  File "main.py", line 6, in counter
    i+=1
UnboundLocalError: local variable 'i' referenced before assignment
Copy the code

Including the integer 1 is also an object, and most importantly, integers in Python are immutable. I and I +1 refer to two different addresses. When I = I + 1 is executed in the inner function, the machine doesn’t know whether you want to create a local variable I or whether you want to do an assignment

We can use nonlocal to declare nonlocal variables. We can use nonlocal to declare nonlocal variables

In addition to using nonlocal, you can also use list, because when you use list, you’re modifying the mutable data type and you’re not declaring new variables