Code Explanation:
1. Function Definition: Outer Function
def make_adder(n):
This defines a function named make_adder that takes one argument n.
n will be used to create a customized "adder" function.
2. Function Definition: Inner Function (Closure)
def adder(x):
return x + n
Inside make_adder, another function adder is defined.
adder takes a parameter x and returns the sum of x and n.
Note: n is not defined inside adder — it's taken from the enclosing scope (i.e., make_adder). This is called a closure.
3. Return the Inner Function
return adder
make_adder returns the function adder, not the result of calling it.
The returned function "remembers" the value of n even after make_adder has finished executing.
4. Create a New Function using make_adder
add5 = make_adder(5)
Calls make_adder(5), which returns a function adder where n is permanently set to 5.
Now, add5 is a function that adds 5 to its input.
5. Call the New Function
print(add5(10))
Calls the add5 function with input 10.
Inside add5, x = 10 and n = 5 (from the closure).
So it computes 10 + 5 = 15.
print outputs:
15
.png)

0 Comments:
Post a Comment