CodeBlanks Logo Icon CodeBlanks

Putting it together

Combine the cart class with a menu loop.

Putting the cart together

In the final lesson we combine the cart. We'll add items, list them and compute the total:

cart = []
cart.append("Apple")
cart.append("Bread")
for item in cart:
    print(item)
prices = [10, 20]
total = 0
for price in prices:
    total += price
print("Total:", total)

This is the skeleton of the cart app: adding, listing and total.

The complete cart

The full cart adds items to a list, iterates over them and sums the prices. This is the skeleton of a small e-commerce app:

cart = ["Apple", "Bread", "Milk"]
for item in cart:
    print(item)
prices = [10, 20, 15]
total = 0
for price in prices:
    total += price
print("Total:", total)

This prints 'Apple', 'Bread', 'Milk' and 'Total: 45'.

Practice Complete the cart

Assign cart = ["Apple", "Bread", "Milk"]. Write for item in cart: print(item). Assign prices = [10, 20, 15] and total = 0. Write for price in prices: total += price. Then print print("Total:", total).

Starter code

main.py
# Complete the cart

Sample solution

main.py
cart = ["Apple", "Bread", "Milk"]
for item in cart:
    print(item)
prices = [10, 20, 15]
total = 0
for price in prices:
    total += price
print("Total:", total)

Expected output

Apple
Bread
Milk
Total: 45

Questions and answers

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

1 What are the three steps of the cart app?

  • Print, wait, exit
  • Input, operation, output
  • Add, list, total Correct answer
  • Open, read, close

Explanation: The cart has adding, listing and total steps.

2 Print the total

Question
print("Total:", ____)
Answer
print("Total:", total)

Explanation: print("Total:", total) prints the total.

3 Match the cart pieces

Term Meaning
append Add an item
for item in cart List items
total += price Addition
print(total) Print the total

All lessons in Beginner