Python Practice › OOP Programs › Program 46

ShoppingCart class

EasyOOP Programs · 46 of 48

Create ShoppingCart with items and total cost, and methods to add and remove items and calculate the total.

Advertisement
Output
{'pen': (10, 5)} 50

Approach

  1. Store items in a dict of name -> (price, quantity).

Solution

Python
class ShoppingCart:    def __init__(self):        self.items = {}     def add(self, name, price, qty=1):        old_qty = self.items.get(name, (price, 0))[1]        self.items[name] = (price, old_qty + qty)     def remove(self, name):        self.items.pop(name, None)     def total_cost(self):        return sum(price * qty for price, qty in self.items.values()) cart = ShoppingCart()cart.add("pen", 10, 3)cart.add("bag", 650)cart.add("pen", 10, 2)cart.remove("bag")print(cart.items, cart.total_cost())
Output
{'pen': (10, 5)} 50

Line by line

Lines 5-7

Adding an item again increases its quantity instead of replacing it.

Lines 12-13

The total is calculated when needed, so it is always up to date.

Learn the concept

New to this topic? Read the lesson, then come back.

More oop programs

← All 48 OOP Programs

Leave a Comment