Python Shopping Cart
## Building an Online Shopping Cart in Python
In object-oriented programming (OOP), classes are highly effective for modeling real-world systems. This tutorial demonstrates how to use Python classes to simulate an online shopping cart.
The shopping cart system will support core e-commerce operations, including:
* Adding items with custom quantities and prices.
* Removing items by name.
* Viewing the current contents of the cart.
* Calculating the total cost of all items in the cart.
---
## Class Design and Implementation
We will define a `ShoppingCart` class. Inside this class, we will manage a list of dictionaries, where each dictionary represents a product with its name, price, and quantity.
### Python Implementation
```python
class ShoppingCart:
def __init__(self):
# Initialize the shopping cart with an empty list of items
self.items = []
def add_item(self, name, price, quantity=1):
# Append a new item dictionary to the items list
self.items.append({'name': name, 'price': price, 'quantity': quantity})
def remove_item(self, name):
# Filter out items matching the specified name using a list comprehension
self.items = [item for item in self.items if item['name'] != name]
def view_cart(self):
# Display the contents of the cart
if not self.items:
print("Your shopping cart is empty.")
else:
for item in self.items:
print(f"{item['name']} - ${item['price']} x {item['quantity']}")
def calculate_total(self):
# Calculate and return the total cost of all items in the cart
return sum(item['price'] * item['quantity'] for item in self.items)
# Example Usage
if __name__ == "__main__":
# Create an instance of the shopping cart
cart = ShoppingCart()
# Add items to the cart
cart.add_item("Apple", 0.5, 3)
cart.add_item("Banana", 0.3, 5)
# View cart and print total
print("--- Cart Contents ---")
cart.view_cart()
print(f"Total: ${cart.calculate_total():.2f}\n")
# Remove an item from the cart
print("--- Removing 'Banana' ---")
cart.remove_item("Banana")
# View cart and print updated total
cart.view_cart()
print(f"Total: ${cart.calculate_total():.2f}")
```
---
## Code Explanation
### 1. The `__init__` Method
The constructor method initializes the `ShoppingCart` instance. It creates an empty list named `self.items` which acts as the database for the cart's items during the session.
### 2. The `add_item` Method
This method accepts three parameters: `name` (string), `price` (float), and `quantity` (integer, defaults to `1`). It packages these attributes into a dictionary and appends it to the `self.items` list.
### 3. The `remove_item` Method
To remove an item, this method uses a **list comprehension** to filter the `self.items` list. It retains only the items whose `'name'` does not match the target name, effectively deleting the target item.
### 4. The `view_cart` Method
This method checks if the cart is empty using Python's implicit boolean evaluation (`if not self.items`). If the list contains items, it iterates through them and prints their details using formatted string literals (f-strings).
### 5. The `calculate_total` Method
This method calculates the grand total by multiplying the price and quantity of each item in the cart. It uses a generator expression inside Python's built-in `sum()` function for optimal performance and clean syntax.
---
## Execution Output
When you run the script, it will produce the following output:
```text
--- Cart Contents ---
Apple - $0.5 x 3
Banana - $0.3 x 5
Total: $2.40
--- Removing 'Banana' ---
Apple - $0.5 x 3
Total: $1.50
```
---
## Production Considerations
While this implementation is excellent for learning OOP basics, consider the following enhancements for production-ready applications:
* **Handling Duplicate Items:** In the current implementation, calling `add_item("Apple", 0.5, 1)` twice will result in two separate entries in the list. In a production system, you should check if the item already exists and increment its quantity instead.
* **Data Validation:** Ensure that `price` and `quantity` are positive numbers before adding them to the cart to prevent logical errors (e.g., negative totals).
* **Encapsulation with Item Classes:** Instead of using raw dictionaries to represent items, you can create a dedicated `Item` class to enforce type safety and cleaner data modeling.
YouTip