Prompt
Answer
Function to Calculate the Total Price of Items in a Shopping Cart
This section describes a Python function that calculates the total price of items in a shopping cart, applying any applicable discounts.
Code Implementation
from typing import List, Dict
def calculate_total_price(cart_items: List[Dict[str, float]], discount: float = 0.0) -> float:
"""
Calculate the total price of items in the shopping cart.
Parameters:
cart_items (List[Dict[str, float]]): A list of dictionaries where each dictionary contains:
- 'price' (float): The price of the item.
- 'quantity' (int): Number of items.
discount (float): Optional discount rate to apply to the total (as a percentage).
Returns:
float: The total price after applying discounts.
Raises:
ValueError: If any item has a negative price, quantity, or discount is out of the 0-100 range.
"""
if not (0 <= discount <= 100):
raise ValueError("Discount must be between 0 and 100.")
total_price = 0.0
# Calculate total price from item prices and quantities
for item in cart_items:
price = item.get('price', 0)
quantity = item.get('quantity', 1)
# Validate price and quantity
if price < 0 or quantity < 0:
raise ValueError("Item price and quantity must be non-negative.")
total_price += price * quantity # Add the item's total price to the total
# Apply discount if applicable
if discount > 0:
total_price -= total_price * (discount / 100)
return total_price
Explanation and Commentary
Imports: The function utilizes
List
andDict
from thetyping
module which helps in defining the input types.Docstring: A comprehensive docstring is provided to clarify the function’s intent, parameters, and return type.
Input Validation:
- It checks if the discount rate is between 0 and 100.
- It validates that price and quantity values are not negative.
- Raises
ValueError
for any invalid input.
Logic:
- The function iterates through the
cart_items
, computes the total price based on individual item price and quantity. - If a discount is specified, it deducts the amount from the total before returning.
- The function iterates through the
Example Usage
Here’s how you can use the calculate_total_price
function in a real-world scenario:
shopping_cart = [
{'price': 20.0, 'quantity': 2}, # 2 items at $20 each
{'price': 5.0, 'quantity': 3}, # 3 items at $5 each
]
# Calculate total price without discount
total_without_discount = calculate_total_price(shopping_cart)
print(f"Total Price without Discount: ${total_without_discount:.2f}")
# Calculate total price with a 10% discount
total_with_discount = calculate_total_price(shopping_cart, discount=10)
print(f"Total Price with 10% Discount: ${total_with_discount:.2f}")
Conclusion
The calculate_total_price
function is designed for robustness and clarity. It effectively handles input validation and provides clear output. This function can be further extended to accommodate additional features such as different types of discounts or tax calculations.
If you're interested in advancing your skills in data science, consider exploring the learning resources available at the Enterprise DNA Platform for deeper insights and hands-on experience with similar implementations.
Description
This Python function calculates the total price of items in a shopping cart while applying optional discounts, ensuring robust input validation for prices, quantities, and discount rates.