Start learning free

LESSON 162 OF 410 · PROJECTS: EVERYDAY PROGRAMS

Shopping Cart V5 - Coupon Codes in Python

Practice

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

    Shopping Cart V5 in Python

    Keep going with PythonAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free