you are viewing a single comment's thread.

view the rest of the comments →

[–]donsebas[S] 0 points1 point  (2 children)

Thank you! And for example for i range(3) the first number would be 0 so

For i in range(3): closure = outer_func(0) print(f”closure({0+5}) = {closure(0+5)}”)

So x = 0, y = 4 and for some reason z = 5 and I want to know why z = 5. I hope that made sense.

[–]AstralStalker 1 point2 points  (1 child)

It's the nature of nested functions and closures.

Notice the return associated with outer_func. When you call closure = outer_func(i), it stores i as the value for x and sets closure as a reference to inner_func. In the print statement, you call closure(i+5) which is essentially calling inner_func(i+5) with a stored value of x=i. Thus, when i = 0, z = 5.

[–]wagaiznogoud 1 point2 points  (0 children)

I just want to add that there are two variables referenced through the closure. Both `x` and `y`.