Python – Can someone interpret the following output?

Can someone interpret the following output?… here is a solution to the problem.

Can someone interpret the following output?

def closure_add():
    x = 3
    def adder():
        nonlocal x
        x+=1
        return x
    return adder
a = closure_add()
b = closure_add()
print(a())
print(b())
print(b())
print(b())

The output is:

4
4
5
6

If the variable “b” that holds the function “adder” remembers the range of the variable (x=3), then the output should not be “4” no matter how many times it is called.

Solution

The link below should provide more information:

In your example, this ultimately boils down to:

  1. Instantiate two separate function objects in variables a and b
  2. You call a once, and it increments the value once
  3. You call b three times to triple the value

Because the value that is incremented in the closure is defined as nonlocal in the method that increments it, the value is stored in the x variable after each change to it in the parent function.

Related Problems and Solutions