CodeBlanks Logo Icon CodeBlanks

Calculating totals

Compute subtotal and tax-inclusive total.

Calculating totals

In this lesson we'll sum the prices of the items in the cart. Prices are kept in a list; a for loop computes the total:

prices = [10, 20, 30]
total = 0
for price in prices:
    total += price
print(total)  # 60

total += price adds price to total at each iteration. This is the basic method for list sums.

Cart total

Imagine the cart has a list of item prices. To compute the cart total we use a for loop:

prices = [10, 20, 30]
total = 0
for price in prices:
    total += price
print("Total:", total)  # Total: 60

This structure is the basis of cart apps: the amount the user pays is computed this way.

Practice Print the total

Assign prices = [10, 20, 30]. Assign total = 0. Write for price in prices: total += price. Print print(total).

Starter code

main.py
# Cart total

Sample solution

main.py
prices = [10, 20, 30]
total = 0
for price in prices:
    total += price
print(total)

Expected output

60

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is the sum of prices = [10, 20]?

  • 30 Correct answer
  • 20
  • 10
  • 200

Explanation: 10 plus 20 is 30.

2 Complete the total loop

Question
total = 0
for price in prices:
    total ____ price
Answer
total = 0
for price in prices:
    total += price

Explanation: += adds price to total at each iteration.

3 Match the total concepts

Term Meaning
total = 0 Initial total
for Loop
+= Addition assignment
print(total) Print the total

All lessons in Beginner