Functions
- Define functions with
defand return values withreturn - Pass positional and keyword arguments
- Set default parameter values
- Understand variable scope: local vs global
Functions are the unit of reuse and testing in every Python codebase. Frameworks like Flask, FastAPI, and pytest are built on decorated functions, and knowing default-argument traps is a common senior-level interview question.
- Using mutable defaults:
def f(x=[]). The list persists across calls; usex=Nonethenx = x or []inside. - Forgetting
return. A function without it returnsNone, silently breaking any caller that expected data. - Mixing positional and keyword args wrong:
f(a=1, 2)raisesSyntaxError. Positional must come before keyword.
A function is a named, reusable block. def defines one. return hands a value back.
Default arguments
excited=False is a default. Callers can override it by name.
Try it
- Write a function
area(width, height)that returns the area of a rectangle. - Add a default for
heightso callingarea(5)returns the area of a 5×5 square.
3 graded exercises
Write the code, click Check. We’ll tell you exactly what to fix.
- Exercise 1
Define a function
area(width, height)that returns (not prints) the area of a rectangle. Then printarea(4, 5). Expected last line:20. - Exercise 2
Rewrite
areawith a default — ifheightis omitted, use the same value aswidth(a square). Then printarea(6)(should be 36) andarea(4, 5)(should be 20). - Exercise 3
Write a function
split_name(full)that takes a string like"Ada Lovelace"and returns a tuple(first, last). Then printsplit_name("Grace Hopper"). Expected includes:('Grace', 'Hopper').