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
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 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.
For a practical file: draw its flowchart or write its algorithm in steps.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises