Functions
Learn how to define and call functions in Python to organize your code into clean, reusable blocks.
Introduction
As programs grow, copying and pasting the same lines of code over and over quickly becomes messy and error-prone. Functions solve this problem by letting you package a block of logic once, give it a name, and reuse it anywhere in your program simply by calling that name.
This lesson focuses on the fundamentals: defining a function with def, calling it, and returning values. Deeper argument-passing techniques like default values, *args, and **kwargs get their own dedicated lesson right after this one.
- How to define a function using def.
- How to call a function and use its result.
- How return sends a value back to the caller.
- How to return multiple values at once.
- What happens when a function has no return statement.
- How to document a function with a docstring.
Why Functions Matter
Functions exist to help you follow the DRY principle — Don't Repeat Yourself. Instead of writing the same calculation in five different places, you write it once inside a function and call that function five times.
Reusability
Write the logic once, use it as many times as you need.
Organization
Breaking a program into functions makes it easier to read and navigate.
Easier Debugging
A bug is easier to find and fix when logic lives in one place instead of many.
Building Blocks
Small functions can be combined to build larger, more powerful programs.
Defining a Function
You define a function using the def keyword, followed by a name, parentheses (which may contain parameters), and a colon. The function's body is indented underneath, just like a loop or if statement.
def greet(name):
message = f"Hello, {name}! Welcome to Python."
print(message)This defines a function named greet that accepts one parameter, name. Nothing happens yet — the code inside only runs once the function is actually called.
def Keyword
Signals to Python that you are defining a new function.
Function Name
A descriptive name, following the same rules as variable names.
Parameters
Placeholders inside the parentheses for values the function needs.
Indented Body
The block of code that runs whenever the function is called.
Calling a Function
Defining a function only creates it — you must call it by writing its name followed by parentheses (with any required values inside) to actually run its code.
def greet(name):
print(f"Hello, {name}! Welcome to Python.")
greet("Maya")
greet("Sam")Hello, Maya! Welcome to Python.
Hello, Sam! Welcome to Python.The same function runs twice with two different values for name — this is exactly the kind of repetition-avoidance functions are built for.
Returning Values
A function that only prints something is useful, but often you want to send a result back so it can be stored, reused, or passed into another calculation. The return statement does exactly that.
def add(a, b):
return a + b
result = add(7, 5)
print("Result:", result)
print("Doubled:", result * 2)Result: 12
Doubled: 24return sends the value a + b back to wherever the function was called. That value is then stored in result, which can be used just like any other variable — including in further calculations.
- print() only displays a value on the screen — it does not give the value back to your code.
- return sends a value back so it can be stored in a variable and reused.
- A function can use both, but only return actually hands data back to the caller.
Returning Multiple Values
Python lets a function return more than one value at once by separating them with commas. Behind the scenes, Python packages these values into a tuple, which you can unpack into separate variables.
def min_max(numbers):
return min(numbers), max(numbers)
scores = [88, 45, 97, 62, 71]
lowest, highest = min_max(scores)
print("Lowest:", lowest)
print("Highest:", highest)Lowest: 45
Highest: 97min_max returns two values as a tuple: (45, 97). Writing lowest, highest = min_max(scores) unpacks that tuple directly into two separate variables in one line.
def min_max(numbers):
return min(numbers), max(numbers)
result = min_max([88, 45, 97, 62, 71])
print(result)
print(type(result))(45, 97)
<class 'tuple'>Functions With No Return
If a function never reaches a return statement — or uses return with no value — Python automatically gives it back the special value None. This is very different from a function that returns 0 or an empty string, which are still real values.
def show_message(text):
print(text)
outcome = show_message("Processing complete")
print("Function returned:", outcome)Processing complete
Function returned: Noneshow_message only prints a message; it has no return statement. So when its result is captured in outcome, that variable ends up holding None.
Docstrings
A docstring is a short description written as a string literal directly under the def line, explaining what the function does. Docstrings are stored by Python and can be viewed later using help() or a function's __doc__ attribute.
def calculate_area(width, height):
"""Return the area of a rectangle given its width and height."""
return width * height
print(calculate_area(4, 5))
print(calculate_area.__doc__)20
Return the area of a rectangle given its width and height.- They explain what a function does without needing to read its full body.
- Tools, editors, and help() can display them automatically.
- They make your code far easier for others — and future you — to understand.
A Note on Parameters
So far every function here has taken plain positional parameters, like name or a, b. Python also lets a parameter have a default value, so it becomes optional when the function is called.
def greet(name, greeting="Hello"):
print(f"{greeting}, {name}!")
greet("Riya")
greet("Omar", "Good morning")Hello, Riya!
Good morning, Omar!This is just a preview — default values, keyword arguments, *args, and **kwargs are covered in full depth in the next lesson, Function Arguments.
Common Mistakes
- Forgetting to call the function — defining greet does nothing until you write greet("Name").
- Confusing print() inside a function with actually returning a value.
- Assuming a function without return gives back an empty string or 0 — it actually returns None.
- Writing return followed by code on the same indentation level that will never run (dead code after return).
- Putting a docstring as a regular comment (#) instead of a proper triple-quoted string.
Best Practices
- Give functions clear, verb-based names like calculate_total or send_email.
- Keep each function focused on doing one clear thing.
- Add a docstring to every function that is not immediately obvious from its name.
- Return values instead of printing them when the result will be used elsewhere in the program.
- Avoid repeating the same block of logic — wrap it in a function instead.
Frequently Asked Questions
What is the difference between a parameter and an argument?
A parameter is the placeholder name written in the function definition (like name). An argument is the actual value you pass in when calling the function (like "Maya").
Can a function return more than two values?
Yes. You can return as many comma-separated values as you like; Python packages them all into one tuple that you can unpack into that many variables.
What does a function return if I do not write a return statement?
It returns None automatically. This applies to any function that reaches the end of its body, or uses a bare return with no value, without explicitly returning something else.
Do I have to write a docstring for every function?
Not strictly required, but it is considered best practice, especially for functions used by other people or that are not perfectly self-explanatory from their name alone.
Can I call a function before it is defined in the file?
No. Python reads files top to bottom, so the def block for a function must appear before the line that calls it.
Key Takeaways
- def defines a function; calling its name with parentheses actually runs it.
- return sends a value back to the code that called the function.
- A function can return multiple values at once, packaged as a tuple.
- A function with no return statement implicitly returns None.
- Docstrings document what a function does and can be viewed with __doc__ or help().
- Functions support the DRY principle by letting you reuse logic instead of repeating it.
Summary
Functions are one of the most important tools for organizing Python code. def lets you package logic under a name, calling that name runs the logic, and return sends a result back for you to use elsewhere.
You also saw that functions can return multiple values as a tuple, that a function without return gives back None, and how docstrings document a function's purpose. Next, you will dive deep into every way Python lets you pass arguments into a function.
- You can define functions with def and call them.
- You understand how return sends values back.
- You can return and unpack multiple values.
- You know what None means for a function with no return.
- You are ready to master function arguments in depth.