Зміст курсу
Introduction to Python Video Course
Introduction to Python Video Course
Recap
Congratulations on completing this section on Python functions! You've gained valuable insights into how functions operate and how they can be applied to real-world scenarios, such as managing grocery store operations.
Here’s a brief recap of what you’ve learned:
Built-in Functions
You explored several essential built-in functions in Python, such as sum()
, max()
, min()
, float()
, int()
, sorted()
, and zip()
. These functions simplify common tasks, like calculating totals or converting data types:
# Example: Using sum() to calculate the total cost prices = [2.99, 1.99, 3.49, 2.50] total_cost = sum(prices) print(f"Total cost: ${total_cost}")
User Defined Functions
You learned how to create your own functions to encapsulate and reuse logic, such as calculating inventory restocks. This skill is vital for organizing and streamlining code in more complex programs:
# Example: Defining a function to calculate restocking needs def restock_quantity(current_stock, desired_stock): restock_qty = desired_stock - current_stock return max(restock_qty, 0) restock_needed = restock_quantity(10, 25) print(f"Restock needed: {restock_needed} units")
Functions With No `return`
We explored functions that perform actions without returning values, such as updating data structures or printing results directly. This type of function is useful when you want to modify existing data or provide immediate feedback to the user:
# Example: Function to update inventory without returning a value def update_inventory(inventory, items_sold): for product, quantity in items_sold.items(): inventory[product] -= quantity print(f"Updated {product} stock: {inventory[product]} units") inventory = {"Milk": 50, "Bread": 30} items_sold = {"Milk": 5, "Bread": 10} update_inventory(inventory, items_sold)
Modifying Functions
You learned advanced techniques for modifying functions, such as using default arguments. These techniques make your functions more flexible and adaptable to different scenarios:
def calculate_final_cost(items, tax_rate=0.07): subtotal = sum(items.values()) tax = subtotal * tax_rate total = subtotal + tax return total # Passing a dictionary directly as an argument products = {"Milk": 2.99, "Bread": 1.79, "Eggs": 3.49} final_total = calculate_final_cost(products) print(f"Final total with tax: ${final_total:.2f}")
Все було зрозуміло?