Python - Functions Basics
Overview
Estimated time: 35–45 minutes
Define functions, choose parameter styles, avoid mutable default pitfalls, and document with docstrings.
Learning Objectives
- Define and call functions with positional and keyword arguments.
- Use parameter kinds (positional-only, keyword-only, *args, **kwargs) appropriately.
- Avoid mutable default arguments; write clear docstrings.
Prerequisites
Defining functions
def add(a, b):
"""Return the sum of a and b."""
return a + b
print(add(2, 3))
print(add(a=2, b=3))
Expected Output:
5\n5
Defaults and pitfalls
def bad_append(x, items=[]): # don't do this
items.append(x)
return items
print(bad_append(1))
print(bad_append(2)) # unexpected: shares list
# Correct approach
def good_append(x, items=None):
if items is None:
items = []
items.append(x)
return items
Expected Output (first two lines):
[1]\n[1, 2]
Common Pitfalls
- Mutable default arguments that persist across calls.
- Overusing *args/**kwargs leading to unclear APIs.
Checks for Understanding
- How do you safely provide a list default parameter?
- What are two benefits of keyword arguments?
Show answers
- Use None as default and initialize inside the function.
- They improve readability and allow argument order flexibility.
Exercises
- Write a function with a keyword-only parameter and call it by name.
- Refactor a function to avoid using *args/**kwargs when not necessary.