16.1 Functions
Separate reusable logic from input and output.
Before you start
Work through the earlier fundamentals chapters. Use a Python 3 interpreter and run each example locally.
Core concepts
Define a function with def, pass values through parameters, and use return to give a result to the caller. A function without an explicit return value returns None. Local names belong to that call unless you deliberately use a broader scope.
Keep filtering and validation separate from file or network operations so they can be tested easily. Type hints describe intended types but do not enforce them at runtime. Default arguments are evaluated once when the function is defined; avoid a mutable default such as items=[].
Worked example
def unhealthy(records, status="critical"):
return [row for row in records if row.get("status") == status]
rows = [{"name": "web-01", "status": "critical"}]
print(unhealthy(rows))
Mini lab
Write is_healthy(status) returning a boolean. Check healthy, critical, and an empty string. The function must return a value rather than print it.
Hint
Start with the smallest input. Print intermediate values while exploring, then replace those prints with checks of the expected result.Show a solution
def is_healthy(status):
return status == "healthy"
assert is_healthy("healthy") is True
assert is_healthy("critical") is False
assert is_healthy("") is False
Knowledge check
Why use None instead of [] as the default for an optional list?
Check your answer
A default list is shared across calls. Create a new list inside the function when the argument is None.Common mistake
Do not mix printing and returning accidentally. Test the returned value directly.
Completion checklist
- Run the example and explain its output.
- Complete the mini lab without copying the solution.
- Test an edge case and explain how the code handles it.
- Answer the knowledge check in your own words.
Add More Questions to This Guide
Know a question that should be here? Share it and help the community!
Open Google Form