Syncing account progress…

Back

Beginner · 12 min

Project: a shopping receipt

Combine a function, a list, a loop, and a condition in one small program.

Calculate a basket subtotal

Break the task into steps you already know. A function can loop over a list and return its total. Keep the running total inside the function but outside the loop.

def basket_total(prices):
    total = 0
    for price in prices:
        total += price
    return total

print(basket_total([4, 6, 3]))

Output

13

Apply a delivery rule

Use the subtotal to choose a fee, then format the final amount. Check the boundary carefully: in this example, a subtotal of exactly twenty also qualifies for free delivery.

subtotal = 13
if subtotal >= 20:
    fee = 0
else:
    fee = 2
print(f"Total: {subtotal + fee}")

Output

Total: 15

Project: a shopping receipt

  1. Calculate the subtotal and choose the delivery fee.
  2. Test the boundary and a second basket after your first solution works.

Try it yourself

Code runs on this device. When you are signed in, drafts sync to your account.

Build the receipt

Complete basket_total(prices) using a loop and return. Keep prices as [4, 6, 3]. Set fee to 0 when the subtotal is at least 20, otherwise 2. Store subtotal plus fee in total and display Total: 15.

Practice