Code Explanation:
Line 1: Function Definition
def choose_fn(op):
This defines a function called choose_fn that takes one parameter op.
op is expected to be a string like 'add' or 'mul'.
Lines 2–5: Conditional Logic with Lambda Return
if op == 'add':
return lambda a, b: a + b
elif op == 'mul':
return lambda a, b: a * b
Case 1: op == 'add'
If op is 'add', it returns a lambda function that takes two arguments a and b, and returns their sum.
Case 2: op == 'mul'
If op is 'mul', it returns a lambda function that multiplies a and b.
These are examples of higher-order functions: functions that return other functions.
Line 6: Function Call
f = choose_fn('mul')
Calls choose_fn with the string 'mul'.
The condition op == 'mul' is true, so the function returns:
lambda a, b: a * b
This lambda is assigned to variable f.
Line 7: Call the Returned Lambda
print(f(4, 5))
Now, f is a lambda that does multiplication.
f(4, 5) → 4 * 5 → 20
So this prints:
Final Output:
20


0 Comments:
Post a Comment