By the end of this lesson, you will be able to define reusable functions in Python using def, pass data via parameters, return results, and set default values for optional arguments.
What it is
A function is a named block of code that performs a specific task. It allows you to encapsulate logic so it can be reused without rewriting the same lines. The mental model is simple: think of a function as a machine where you input raw materials (parameters), process them internally, and output a finished product (return value).
Key terms include:
- Definition: Creating the function using the
defkeyword. - Call: Executing the function by using its name followed by parentheses.
- Parameter: A variable listed inside the parentheses in the function definition.
- Argument: The actual value sent to the function when it is called.
Why it matters
- Reusability: Write code once and use it multiple times across your program.
- Maintainability: Fix bugs or update logic in one place rather than searching through scattered code.
- Readability: Break complex problems into smaller, named steps that describe intent clearly.
- Modularity: Isolate functionality, making it easier to test individual components independently.
Syntax or steps
The basic structure requires the def keyword, a unique name, parentheses containing parameters, a colon, and an indented body.
- Start with
def. - Add the function name (use lowercase with underscores).
- Include parameters inside parentheses.
- End the line with a colon
:. - Indent the code block that follows.
- Use
returnto send a result back to the caller.
Example
def calculate_area(width, height=10):
"""Calculate the area of a rectangle."""
area = width * height
return area
# Call with two arguments
result1 = calculate_area(5, 8)
print(f"Area with explicit height: {result1}")
# Call with one argument (uses default height=10)
result2 = calculate_area(5)
print(f"Area with default height: {result2}")
Explanation:
def calculate_area...defines the function.widthis a required parameter;height=10is an optional parameter with a default value.- The body calculates the product and stores it in
area. return areasends the calculated value back to the variable calling the function.- The first call passes both values. The second call omits
height, so Python automatically uses10.
Common mistakes
- Forgetting to return: If you omit
return, the function returnsNone. Ensure you explicitly return the result if you need to use it later. - Mutable default arguments: Never use lists or dictionaries as default values (e.g.,
def func(items=[])). This causes unexpected behavior because the list persists between calls. UseNoneinstead and initialize inside the function. - Indentation errors: Python relies on indentation. All code inside the function must be indented consistently (usually 4 spaces).
- Calling before defining: You cannot call a function before the interpreter has read its definition.
When to use it
Functions are essential for any logic used more than once or any task that benefits from isolation. Compare them with inline code blocks:
| Feature | Function | Inline Code |
|---|---|---|
| Reusability | High | Low |
| Testing | Easy (unit tests) | Hard |
| Overhead | Slight performance cost | None |
| Best For | Complex or repeated logic | Simple, one-off calculations |
Practice
Guided Exercise: Create a function named greet_user that takes a name parameter and prints "Hello, [name]!". Call it with your own name.
Challenge: Modify calculate_area to accept a third parameter shape with a default value of "rectangle". If shape is "square", ignore the height and square the width. Hint: Use an if statement inside the function.
Quick check
Question: What happens if you call a function that does not have a return statement?
Answer: The function executes its code but returns None implicitly.
Summary
Functions are the building blocks of organized Python code, allowing you to bundle logic into reusable units. By mastering parameters, return values, and defaults, you create flexible tools that make your programs cleaner, easier to debug, and scalable.