Start learning free

LESSON 159 OF 410 · PROJECTS: EVERYDAY PROGRAMS

Shopping Cart V2 - Tax and Discount in Python

Practice

Add a discount and sales tax to a single-item purchase using integer math.

You start with:

item = "Coffee Mug"
price = 12
quantity = 3
tax_rate = 8
discount = 5

Build:

Subtotal: $36
Discount: $5
Tax: $2
Total: $33

Rules:

  • subtotal = price * quantity.
  • after_discount = subtotal - discount (the discount is a flat amount taken off before tax).
  • tax = after_discount * tax_rate // 100 (integer division, which rounds down). The tax is charged on the discounted amount.
  • total = after_discount + tax.
  • Build four lines (Subtotal, Discount, Tax, Total) and join them with a newline "\n" into one string result. Just store the text in result; you do not need to print it.

Compute the four numbers (subtotal, after_discount, tax, total) before formatting.

Use str() to convert each number while building the lines.

Use // so the tax is a whole number rounded down.

item = "Coffee Mug"
price = 12
quantity = 3
tax_rate = 8
discount = 5

subtotal = price * quantity
after_discount = subtotal - discount
tax = after_discount * tax_rate // 100
total = after_discount + tax
line1 = "Subtotal: $" + str(subtotal)
line2 = "Discount: $" + str(discount)
line3 = "Tax: $" + str(tax)
line4 = "Total: $" + str(total)
result = line1 + "\n" + line2 + "\n" + line3 + "\n" + line4

STEP 1 OF 9
    Ctrl + Enter to check

    Shopping Cart V2 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