Part 05 / Topic 9 of 9
Putting it together: discount calculator
Real-world example: an online shop with a default discount, an optional coupon (keyword-only) and 18% GST.
def final_price(price: float, discount: float = 0.10, *, coupon: str | None = None,
gst: float = 0.18) -> float:
"""Return the price after discount, coupon and GST."""
price = price * (1 - discount)
if coupon == "SAVE100":
price = max(price - 100, 0)
return round(price * (1 + gst), 2)
print(final_price(1000)) # 1062.0
print(final_price(1000, 0.20)) # 944.0
print(final_price(1000, coupon="SAVE100")) # 944.0
Full program: examples/01_discount_calculator.py.
Done here? The practice set for Part 5 — 8 exercises with solutions — is on the part page.