Functions: Reusable Blocks of Logic
Package logic into reusable functions using def, parameters, defaults, and return.
What you'll learn
- Define functions with def, parameters, and a return value
- Use default argument values and keyword arguments
- Write a docstring describing what a function does
Prerequisites
Explanation
As programs grow, copying and pasting the same logic in multiple places becomes a liability — fix a bug in one copy and forget the other three, and you have inconsistent behavior. Functions solve this by giving a block of logic a name you can call whenever you need it.
Defining a function. The def keyword starts a function definition, followed by a name, parentheses containing zero or more parameters, and a colon. Everything indented underneath is the function's body:
def greet(name):
return f"Hello, {name}!"
Calling greet("Maya") runs that body with name bound to "Maya", and produces the value after return. The value passed in when calling — "Maya" — is technically called an argument; the placeholder name inside the definition is the parameter. The distinction rarely matters day to day, but the vocabulary shows up in error messages.
return vs. print. A common early confusion is treating print() and return as the same thing. print() only displays a value — it doesn't hand anything back to whatever called the function. return is what actually produces a usable result: it hands a value back to the caller, ends the function immediately, and that value can be stored in a variable, passed to another function, or used in a calculation. A function with no return statement implicitly returns None.
Default arguments. Writing def greet(name, greeting="Hello") gives greeting a fallback value used whenever the caller doesn't supply one. greet("Sam") uses the default; greet("Sam", greeting="Welcome") overrides it. Arguments supplied by name like this (greeting="Welcome") are called keyword arguments, and they can appear in any order as long as they come after any purely positional ones.
Docstrings. Immediately after the def line, a triple-quoted string ("""like this""") documents what the function does, its parameters, and what it returns. This isn't just a comment — tools, editors, and the built-in help() function can read it directly, so it's worth writing one for anything beyond a throwaway script.
Why this matters for everything that follows. Functions are the unit almost every other Python feature builds on: modules are collections of functions (and classes), tests call functions and check what they return, and classes attach functions ("methods") to objects. Getting comfortable with parameters, defaults, and return now pays off in every lesson from here forward.
Example
Two functions: one with a default parameter and a docstring, one computing a rectangle's area.
def greet(name, greeting="Hello"):
"""Return a friendly greeting for the given name."""
return f"{greeting}, {name}!"
print(greet("Maya"))
print(greet("Sam", greeting="Welcome"))
def area_of_rectangle(width, height):
"""Return the area of a rectangle given its width and height."""
return width * height
print(area_of_rectangle(3, 4))Try it yourself
Change the default greeting, or call greet() with a third name, then press Run.
Code editor. Press Escape then Tab to leave the editor if keyboard focus becomes trapped. Press Control+Shift+M inside the editor to toggle Tab-key focus trapping.
Guided exercise
Guided exercise
Complete calculate_total so it returns subtotal minus discount.
Checks: calculate_total(10, 3) returns 30 · calculate_total(10, 3, discount=5) returns 25 · plus 1 hidden check
Code editor. Press Escape then Tab to leave the editor if keyboard focus becomes trapped. Press Control+Shift+M inside the editor to toggle Tab-key focus trapping.
Stuck? Get a hint.
Independent exercise
Independent exercise
Write bmi_category(weight_kg, height_m) that computes BMI = weight_kg / (height_m ** 2) and returns 'underweight' (bmi < 18.5), 'normal' (18.5-24.9), 'overweight' (25-29.9), or 'obese' (30+).
Checks: bmi_category(50, 1.8) returns 'underweight' · bmi_category(70, 1.75) returns 'normal' · bmi_category(85, 1.7) returns 'overweight' · plus 1 hidden check
Code editor. Press Escape then Tab to leave the editor if keyboard focus becomes trapped. Press Control+Shift+M inside the editor to toggle Tab-key focus trapping.
Stuck? Get a hint.
Common mistakes
- Using print() inside a function instead of return, then being surprised the result can't be stored in a variable.
- Forgetting that a function without an explicit return statement returns None.
- Placing a parameter with a default value before a parameter without one, which Python rejects as a SyntaxError.
- Assuming a docstring is just a comment — it's a real string, retrievable via help(function_name) or function_name.__doc__.
Knowledge check
Takeaway
Functions turn a block of logic into a reusable, named tool: define it once with def and return, then call it wherever you need that result.
Summary
Functions are defined with def, take parameters (which may have default values), and hand a result back to the caller via return — distinct from print(), which only displays output. Docstrings document a function's purpose and are readable through help(). Functions are the foundational unit that modules, tests, and classes all build on.
References
Your notes
Notes save automatically.
Finished this lesson?
Mark it complete to track your progress and schedule a future review.
AI tutor
The optional AI tutor isn't enabled in this deployment. All lessons, exercises, quizzes, and search work fully without it.