Calculating totals
- Python course
- Beginner
- Lesson 50/116
- 6 min
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) # 60total += 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: 60This 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
# Cart totalSample solution
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
total = 0
for price in prices:
total ____ price
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 |