Now that we've explored the building blocks of functions – defining them, passing arguments, and returning values – it's time to see how they come together in a practical scenario. Imagine you're building a simple system to manage a small online store. You'll need to perform common tasks like calculating prices, applying discounts, and displaying order summaries. Functions are perfect for encapsulating these operations, making your code cleaner, more organized, and easier to maintain.
Let's create a mini-application that simulates calculating the total cost of an order, including a potential discount. We'll define a few functions to handle different parts of this process.
def calculate_item_price(base_price, quantity):
return base_price * quantityFirst, we define a function calculate_item_price that takes the base_price of an item and its quantity as input. It then returns the total price for that item by multiplying them. This function is simple and does one specific job well.
def apply_discount(total_amount, discount_percentage):
if discount_percentage > 0 and discount_percentage <= 100:
discount_factor = 1 - (discount_percentage / 100)
return total_amount * discount_factor
else:
return total_amountNext, we have apply_discount. This function takes the total_amount and a discount_percentage. It checks if the discount is valid (between 0 and 100) and, if so, calculates the discounted price. Otherwise, it returns the original total amount. This function demonstrates conditional logic within a function.
def display_order_summary(item_details, final_price):
print("--- Order Summary ---")
for item, price in item_details.items():
print(f"{item}: ${price:.2f}")
print(f"Total Amount: ${final_price:.2f}")
print("---------------------")Our third function, display_order_summary, is responsible for presenting the order information neatly. It takes a dictionary item_details (mapping item names to their calculated prices) and the final_price to display. Notice the use of f-strings for formatted output.
Now, let's see how we can use these functions together to process an order.
apple_price = 1.50
apple_quantity = 5
banana_price = 0.75
banana_quantity = 10
coupon_discount = 10 # 10% discount
apples_total = calculate_item_price(apple_price, apple_quantity)
bananas_total = calculate_item_price(banana_price, banana_quantity)
order_items = {
"Apples": apples_total,
"Bananas": bananas_total
}
subtotal = sum(order_items.values())
final_order_price = apply_discount(subtotal, coupon_discount)
display_order_summary(order_items, final_order_price)In this main part of our script, we first define some initial prices and quantities. We then call calculate_item_price for each item and store the results in the order_items dictionary. We calculate the subtotal by summing up the prices in the dictionary. Finally, we apply any coupon_discount using our apply_discount function and then display the complete summary using display_order_summary.
graph TD;
A[Start Program] --> B{Define Functions};
B --> C[calculate_item_price];
B --> D[apply_discount];
B --> E[display_order_summary];
C --> F[Calculate Item Cost];
D --> G[Apply Discount];
E --> H[Display Summary];
F --> I[Process Order];
G --> I;
H --> J[End Program];
I --> H;
This example illustrates the power of functions: they break down a complex problem into smaller, manageable, and reusable pieces. Each function has a clear purpose, making our code more readable, testable, and easier to debug. If we wanted to add a new item, we'd just call calculate_item_price again. If we wanted to change how discounts are applied, we'd only need to modify the apply_discount function.