Code Explanation:
Line 1 — Define a function factory
def make_discount(discount_percent):
Creates a function (make_discount) that takes a percentage (e.g., 10 for 10%).
This outer function will produce a specialized discounting function and remember the given percentage.
Lines 2–3 — Define the inner function (the actual discounter)
def discount(price):
return price * (1 - discount_percent / 100)
discount(price) is the function that applies the discount to any price.
It computes the multiplier 1 - discount_percent/100.
For discount_percent = 10, that’s 1 - 0.10 = 0.90, so it returns price * 0.9.
Note: discount_percent comes from the outer scope and is captured by the inner function—this is a closure.
Line 4 — Return the inner function
return discount
Hands back the configured discount function (with the chosen percentage baked in).
Line 5 — Create a 10% discount function
ten_percent_off = make_discount(10)
Calls the factory with 10, producing a function that will always apply 10% off.
ten_percent_off is now effectively: lambda price: price * 0.9.
Line 6 — Use it and print the result
print(ten_percent_off(200))
Computes 200 * 0.9 = 180.0
Printed output:
180.0
Download Book - 500 Days Python Coding Challenges with Explanation
.png)

0 Comments:
Post a Comment