Start learning free

LESSON 189 OF 287 · PROJECTS: EVERYDAY PROGRAMS

Shopping Cart V5 in Python: Coupon Codes with dict.get

Practice Read the full explanation

Use a dictionary as a fast lookup table for coupon discounts.

You start with:

subtotal = 100
coupon = "SAVE20"
coupons = {"SAVE10": 10, "SAVE20": 20, "SAVE50": 50}

Build:

Total: $80

Rules:

  • Look up coupon in coupons. If it is there, its value is the discount; if it is not (an unknown code), the discount is 0.
  • total = subtotal - discount.
  • Build the text "Total: $<total>" (e.g. "Total: $80"; an unknown coupon would give "Total: $100").
  • Store it in result; you do not need to print it.

Use coupons.get(coupon, 0): it returns the value if the key is present, or 0 if it is missing.

Use str(total) to convert the number before concatenating it.

subtotal = 100
coupon = "SAVE20"
coupons = {"SAVE10": 10, "SAVE20": 20, "SAVE50": 50}

discount = coupons.get(coupon, 0)
total = subtotal - discount
result = "Total: $" + str(total)

STEP 1 OF 3
    Ctrl + Enter to check

    PYTHON · PROJECTS: EVERYDAY PROGRAMS

    Shopping Cart V5 in Python, explained

    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

    1. 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.
    2. Compute total. subtotal - discount is what the customer pays.
    3. Build result. The text Total: $ followed by total turned into text with str().

    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:

    • get against square brackets. coupons["FREE"] raises KeyError: 'FREE'. coupons.get("FREE", 0) returns 0. Without a default, get returns None, and subtracting None from a number would raise a TypeError, so the default is what makes the code safe.
    • The default is only for missing keys. If a code is in the table, get returns 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 coupons is True and "FREE" in coupons is False. This lesson does not need it, because get folds 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 give Total: $100.
    • The other known codes. "SAVE10" gives Total: $90 and "SAVE50" gives Total: $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 with max(0, ...).
    • Using coupons[coupon]. It works for known codes and crashes for unknown ones.
    • Forgetting str(). "Total: $" + total raises a TypeError, because total is an integer.
    • Swapping the arguments. get takes the key first and the default second.

    Testing

    • coupon = "SAVE20" gives Total: $80.
    • coupon = "SAVE10" gives Total: $90.
    • coupon = "SAVE50" gives Total: $50.
    • coupon = "save20" gives Total: $100.
    • coupon = "FREE" gives Total: $100.
    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free