Problem overview
Version 5 of the cart applies a coupon. The starting variables are subtotal (100), coupon, the code the shopper typed ("SAVE20"), and coupons, a dictionary that maps each valid code to the amount it takes off. A known code subtracts its amount from the subtotal. An unknown code takes nothing off. The program stores a one-line receipt in result.
With "SAVE20" the discount is 20 and the receipt is:
Total: $80
With a code that isn't in the dictionary, the discount is 0 and the receipt reads Total: $100.
Approach: a dictionary as a lookup table
A coupon code is a key, and its discount is the value. That is what a dictionary is for: given the key, it finds the value directly, however many codes the table holds. The alternative is a chain of if coupon == "SAVE10", elif branches, which has to grow with every new code.
The only problem is the shopper who types a code the table doesn't know. Reading coupons[coupon] then raises a KeyError. The get method solves that by taking a default to return when the key is missing.
Step by step
- Look up the discount.
coupons.get(coupon, 0)returns the value for the code, or 0 when the code is missing. An unknown code therefore means a discount of 0 and no error. - Compute
total.subtotal - discountis what the customer pays. - Build
result. The textTotal: $followed bytotalturned into text withstr().
The solution in Python
subtotal = 100
coupon = "SAVE20"
coupons = {"SAVE10": 10, "SAVE20": 20, "SAVE50": 50}
discount = coupons.get(coupon, 0)
total = subtotal - discount
result = "Total: $" + str(total)
Details worth knowing:
getagainst square brackets.coupons["FREE"]raisesKeyError: 'FREE'.coupons.get("FREE", 0)returns 0. Without a default,getreturnsNone, and subtractingNonefrom a number would raise aTypeError, so the default is what makes the code safe.- The default is only for missing keys. If a code is in the table,
getreturns its stored value, even when that value is 0. - Keys are compared exactly. Dictionary keys are case-sensitive, so
"save20"is not"SAVE20". It is an unknown code and takes nothing off. - Checking with
in."SAVE10" in couponsisTrueand"FREE" in couponsisFalse. This lesson does not need it, becausegetfolds the check and the lookup into one call. - Integers all the way. The discount is a flat amount, not a percentage, so the arithmetic stays in whole numbers.
Edge cases and common mistakes
- An unknown code.
"FREE","save20"and the empty string""all giveTotal: $100. - The other known codes.
"SAVE10"givesTotal: $90and"SAVE50"givesTotal: $50. - A discount larger than the subtotal. With a subtotal of 30 and "SAVE50", the code gives
Total: $-20. The lesson has no guard against a negative total, and its tests don't reach this case. A real shop would clamp the total at 0 withmax(0, ...). - Using
coupons[coupon]. It works for known codes and crashes for unknown ones. - Forgetting
str()."Total: $" + totalraises aTypeError, becausetotalis an integer. - Swapping the arguments.
gettakes the key first and the default second.
Testing
coupon = "SAVE20"givesTotal: $80.coupon = "SAVE10"givesTotal: $90.coupon = "SAVE50"givesTotal: $50.coupon = "save20"givesTotal: $100.coupon = "FREE"givesTotal: $100.
