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.