Code Explanation:
1. Function Definition: counter()
def counter():
x = [0]
A function named counter is defined.
Inside it, a list x with a single element 0 is created.
The list is used instead of an integer because lists are mutable, which allows the inner function to modify the value.
2. Inner Function: inc()
def inc():
x[0] += 1
return x[0]
inc() is a nested function (also called a closure).
It accesses the variable x from the outer scope (nonlocal variable).
x[0] += 1 increments the first element of the list.
It then returns the incremented value.
3. Returning the Closure
return inc
The counter() function returns the inner function inc, not its result.
This means calling counter() gives you a new counter function that you can call repeatedly.
4. Using the Counter
c = counter()
c now holds the inc function.
But it remembers the x = [0] from when counter() was first called — this is what makes it a closure.
5. Calling the Counter Twice
print(c(), c())
First call: c() → x[0] becomes 1, returns 1
Second call: c() → x[0] becomes 2, returns 2
So, the output is:
1 2
Final Output
1 2
.png)

0 Comments:
Post a Comment