Functions, Parameters, and Return Values
Functions bundle repeatable logic into reusable blocks, keeping your codebase organized and testable.
What is it?
In Python, a function is defined using the `def` keyword, followed by the function name, parentheses containing parameters, and a colon.
Why is it used?
Eliminates duplicate code, divides large problems into bite-sized units, and facilitates unit testing.
Detailed Explanation
Components:
• Parameters: Variables listed inside the parentheses in the function definition.
• Arguments: Actual values passed into the function when calling it.
• Positional vs Keyword Arguments: You can specify argument names explicitly when calling: `calculate(price=2500, discount=10)`.
• Default Parameters: `def greet(name="Student"):`.
• Docstrings: Triple-quoted documentation strings placed immediately after `def`.
Syntax Structure
Syntax Blueprint
def function_name(param1, param2=default):
"""Docstring explaining what the function does."""
return result
Code Example
PYTHON Code
def calculate_bundle_pricing(course_prices, bundle_discount_pct=25):
"""
Calculates original total, discount savings, and final price.
Returns a dictionary of financial results.
"""
original_total = sum(course_prices)
savings = (original_total * bundle_discount_pct) / 100
final_price = original_total - savings
return {
"original_total": original_total,
"savings": round(savings),
"final_price": round(final_price)
}
# Positional arguments with default discount
result1 = calculate_bundle_pricing([2500, 2500, 2500])
print("Standard 3-Course Bundle:", result1)
# Keyword argument overriding default discount
result2 = calculate_bundle_pricing([2500, 2500], bundle_discount_pct=15)
print("Custom 2-Course Bundle:", result2)
Explanation of the Code
• Includes docstring explaining function behavior.
• Demonstrates default parameter `bundle_discount_pct=25`.
• Returns structured dictionary with calculated figures.
Expected Output
Standard 3-Course Bundle: {'original_total': 7500, 'savings': 1875, 'final_price': 5625}
Custom 2-Course Bundle: {'original_total': 5000, 'savings': 750, 'final_price': 4250}
Real-World Application
Used across accounting engines, user service layers, and business logic controllers.
Common Mistakes to Avoid
• Using a mutable object (like a list `[]` or dict `{}`) as a default argument parameter (default arguments are evaluated once at module load, leading to shared state bugs!). Use `param=None` instead.
• Forgetting the `return` statement (function returns `None`).
Quick Practice Challenge
Write a function `is_even(number)` that returns `True` if a number is even, and `False` otherwise.
Key Takeaways
• Define functions with `def name(params):`.
• Always write a triple-quoted docstring explaining inputs and outputs.
• Never use mutable objects (`[]`) as default parameter values.