How to Define a Function in Python with def
A function gives a name to a piece of work so you can run it whenever you need it, with different values each time. In Python you write one with def, list the values it needs in brackets and send the answer back with return.
Syntax
def <name>(<parameter>, <parameter>):
<body>
return <value>
| Part | What it does |
|---|---|
def <name> | Starts a function definition and names the function. |
(<parameter>, ...) | The values the function receives, each with a name used inside the body. |
: and the indented <body> | The code that runs on each call. It must be indented. |
return <value> | Ends the call and hands <value> back to the caller. |
The Python tutorial: "The keyword def introduces a function definition. It must be followed by the function name and the parenthesized list of formal parameters. The statements that form the body of the function start at the next line, and must be indented."
The Example
The example defines area, which multiplies a width by a height, and calls it for two rectangles.
Prerequisites
- uv and Python. This guide uses uv 0.13.10 with Python 3.15.2.
Step 1: Write the Function
Create a file named main.py:

def area(width, height):
return width * height
print(area(3, 4))
print(area(10, 2))
def area(width, height):defines a function with two parameters.return width * heightsends the product back.area(3, 4)calls it withwidthset to3andheightset to4.
Step 2: Run It
uv run python main.py
12
20

One definition, two calls, two answers. The command is the same in zsh, bash and PowerShell.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
Leaving out the colon after def area(width, height) | SyntaxError: expected ':' | End the def line with : |
Calling the function above its def | NameError: name 'area' is not defined | Define functions before the code that calls them |
Forgetting return | The call gives None | Return the result |
Passing too few values, as in area(3) | TypeError: area() missing 1 required positional argument: 'height' | Pass one value for each parameter |
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
None is printed instead of a number | The function has no return | Add return with the value |
IndentationError near the function | The body isn't indented consistently | Indent every body line by four spaces |
FAQ
Can a parameter have a default value?
Yes: def area(width, height=1): lets callers leave height out.
Why two blank lines after the function?
Python's style guide, PEP 8, asks for two blank lines around top-level functions. Python itself doesn't require them.
Conclusion
def name(parameters): defines a function, its indented body does the work and return hands back the answer. Call it with name(arguments) as often as you need.
Additional Resources
- Defining Functions, in the Python tutorial.
- Function definitions, in the Python language reference.
