Python Program for a Shopping Cart Using a Class
Intermediate · Classes and objects
This program builds a shopping cart as a class. Items can be added with a price and a quantity, or removed, and the program prints a bill with the total, giving a discount when the total crosses a limit. The cart keeps its items in a dictionary inside the object.
Program
shopping_cart_class.py
class ShoppingCart:
def __init__(self):
self.items = {} # item name -> [price, quantity]
def add(self, name, price, quantity=1):
if name in self.items:
self.items[name][1] += quantity # already in the cart: add more
else:
self.items[name] = [price, quantity]
def remove(self, name):
if name in self.items:
del self.items[name]
def total(self):
return sum(price * quantity for price, quantity in self.items.values())
cart = ShoppingCart()
cart.add("Notebook", 60, 5)
cart.add("Pen", 20, 10)
cart.add("Water bottle", 250)
cart.add("Pen", 20, 2) # 2 more pens
cart.add("School bag", 899)
cart.remove("Water bottle")
for name, (price, quantity) in cart.items.items():
print(f"{name}: {quantity} x Rs. {price} = Rs. {price * quantity}")
total = cart.total()
discount = total * 10 // 100 if total >= 1000 else 0 # 10% off on Rs. 1000 or more
print("Total: Rs.", total)
print("Discount: Rs.", discount)
print("To pay: Rs.", total - discount)
Output
Notebook: 5 x Rs. 60 = Rs. 300 Pen: 12 x Rs. 20 = Rs. 240 School bag: 1 x Rs. 899 = Rs. 899 Total: Rs. 1439 Discount: Rs. 143 To pay: Rs. 1296
How it works
- The cart stores its items in a dictionary,
self.items, where each item name maps to a list of[price, quantity]. add()increases the quantity when the item is already in the cart, so adding pens twice gives one line with 12 pens.remove()deletes an item withdel, after checking that it is in the cart, so a missing name causes no error.total()multiplies the price by the quantity for each item and adds the results.- The total of Rs. 1439 is at least Rs. 1000, so a 10% discount is given;
// 100keeps it a whole number of rupees.
Another way to write it
Items as objects too
Items as objects too
class Item:
def __init__(self, name, price, quantity):
self.name = name
self.price = price
self.quantity = quantity
def cost(self):
return self.price * self.quantity
class Cart:
def __init__(self):
self.items = []
def add(self, item):
self.items.append(item)
def __len__(self):
return len(self.items)
cart = Cart()
cart.add(Item("Notebook", 60, 5))
cart.add(Item("Pen", 20, 12))
print("Items in the cart:", len(cart))
print("Total: Rs.", sum(item.cost() for item in cart.items))
Output
Items in the cart: 2 Total: Rs. 540
Here each item is an object of its own class, and the cart holds a list of them. Defining __len__ makes len(cart) work, just as it does for a list.
Try it yourself
Add a method change_quantity(name, quantity) and use it to set the notebooks to 3.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises