Learn What def is in Python: Absolute Beginners Tutorial

Before you can build anything meaningful in Python, you need to know how to package code so it can be reused. That starts with def — the keyword Python uses to define functions. This tutorial explains exactly what def does, why it exists, and how to write your first function from scratch.

Every time you write a program, you will end up running the same group of instructions more than once. Copying those instructions every time you need them is not just tedious — it creates bugs, because a change in one copy does not update the others. Functions solve this problem. The def keyword is how you tell Python you are about to create one.

What def Actually Means

def is short for define. When Python encounters a def statement, it does not run the code inside immediately. Instead, it reads the instructions, packages them up as a function object, and stores that object in memory under the name you gave it. Nothing executes until you call the function.

This distinction matters. Reading a recipe is not the same as cooking dinner. def writes the recipe. Calling the function cooks it.

Note

def is a reserved keyword in Python. You cannot use it as a variable name, class name, or anything else. Python already owns it.

Here is the simplest function you can write:

python
def say_hello():
    print("Hello, world!")

This def statement creates a function named say_hello. The function has no parameters — the parentheses are empty — and its body contains a single print call. After Python reads these two lines, say_hello exists as a function object in memory. It has not printed anything yet.

To actually run it:

python
say_hello()     # Output: Hello, world!

The parentheses after the name are what trigger execution. Without them, you would be referencing the function object itself, not calling it.

"A function definition is a compound statement that binds a function object to a name." — Python Language Reference
code builder click a token to place it

Build a valid Python function definition for a function named greet with no parameters:

your code will appear here...
) return def : class greet (
Why: A def statement always follows this order: the keyword def, then the function name, then parentheses (), then a colon :. The colon is required — it signals that an indented body follows. class and return are not part of a function header.

The Anatomy of a Python Function

Every function defined with def has the same structural components. Understanding each one helps you write functions correctly and read other people's code without confusion.

Anatomy of a Python def statement — keyword, name, parameter, colon, and indented body.

The components break down like this:

Purpose
Signals the start of a function definition. Required — there is no substitute keyword.
Example
def is always the very first token on the line.
Purpose
The identifier Python binds the function object to. This is the name you use to call it later.
Convention
Use lowercase letters with underscores separating words: calculate_area, send_email.
Purpose
Parentheses are required even when there are no parameters. Parameters listed here act as local variable names inside the function body.
Example
def greet(): — no parameters. def greet(name): — one parameter.
Purpose
Marks the end of the function header. Missing it causes a SyntaxError immediately.
Analogy
Think of it as saying "here comes the body."
Purpose
The indented block containing all the code the function runs when called. Every line must be indented consistently — typically four spaces.
Minimum
A body must contain at least one statement. Use pass to create a valid but empty function body as a placeholder.
spot the bug click the line that contains the bug

The function below has a syntax error that prevents it from running. Find the line that is wrong.

1 def calculate_total(price, tax)
2 total = price + (price * tax)
3 return total
4
5 result = calculate_total(100, 0.08)
The fix: Add a colon at the end of line 1: def calculate_total(price, tax):. The colon is required after every function header. Python uses it to know that an indented body follows. Omitting it raises a SyntaxError before any code runs.

Parameters, Arguments, and Return Values

A function that always does the same thing is useful but limited. Parameters make functions flexible by letting callers pass data in. Return values let functions send data back out.

Parameters vs. Arguments

These two words are often used interchangeably, but they mean different things. A parameter is the variable name listed in the def line. An argument is the actual value passed when the function is called.

python
def add(x, y):          # x and y are parameters
    return x + y

result = add(3, 4)      # 3 and 4 are arguments
print(result)           # Output: 7

When Python executes the add(3, 4) call, it assigns 3 to x and 4 to y inside the function's local scope. Those assignments only exist while the function runs.

The return Statement

A function does not have to return a value. If you write no return statement — or just return with nothing after it — Python returns None automatically. When a function does return a value, the caller receives it and can store it, print it, or use it as input to another function.

python
# Function with a return value
def square(n):
    return n * n

# Function with no return value
def announce(message):
    print(f"Announcement: {message}")

value = square(5)       # value is 25
announce("Done!")       # Prints the message, returns None
Pro Tip

Once Python executes a return statement, the function stops immediately. Any code after return in the same block will not run. This can be useful — you can use an early return to exit a function when a condition is met.

Watch Out

A common mistake is calling a function before it is defined. Python reads files top to bottom. If you call greet() on line 3 and the def greet(): statement appears on line 10, you will get a NameError. Always define before you call — unless you are working inside a function that is itself called later.

check your understanding question 1 of 4

How to Define a Function in Python Using def

Follow these steps to write a complete Python function from scratch. Each step builds on the last.

  1. Write the def line

    Start the line with def, followed by your function name, then parentheses, then a colon. The name should describe what the function does. Example: def greet():

  2. Add the function body

    On the next line, indent by four spaces and write the code you want to run. Every line of the body must share the same indentation level. A bare pass statement works as a placeholder if you have nothing yet.

  3. Add a parameter (optional)

    Place a variable name inside the parentheses on the def line. Multiple parameters are separated by commas. Each parameter becomes a local variable available inside the function body. Example: def greet(name, title):

  4. Return a value (optional)

    Use return followed by an expression to send a value back to the caller. Without return, Python automatically returns None. Place return at whatever point the function has finished its work.

  5. Call the function

    Write the function name followed by parentheses below the definition. Pass arguments inside the parentheses if the function has parameters. Store the result in a variable if the function returns a value. Example: message = greet("Alex", "Dr.")

python
# Step 1 and 2: def line + body
def greet():
    print("Hello!")

# Step 3: adding a parameter
def greet(name):
    print(f"Hello, {name}!")

# Step 4: returning a value
def greet(name):
    return f"Hello, {name}!"

# Step 5: calling the function
message = greet("Alex")
print(message)          # Output: Hello, Alex!

Python Learning Summary Points

KEY TAKEAWAYS

  • def is Python's keyword for defining a function. It stores the function in memory without executing it.
  • Every function header requires a colon at the end. Forgetting it causes a SyntaxError.
  • The function body must be indented consistently — four spaces is the standard.
  • Parentheses are required even when the function takes no parameters.
  • Parameters are the variable names in the def line. Arguments are the values passed during a call.
  • Without a return statement, Python returns None automatically.
  • Functions must be defined before they are called in the file's top-to-bottom execution order.
  • A function can be called any number of times after it is defined — that is the whole point.

Frequently Asked Questions

def is a keyword that tells Python you are defining a new function. It stands for define. When Python sees def, it reads the function name, parameters, and body and stores them in memory so the function can be called later.

The syntax is: def function_name(parameters): followed by an indented block of code. The colon at the end of the def line is required. The indented body can contain any valid Python statements.

No. If a function has no return statement, Python automatically returns None. A function can perform side effects such as printing to the screen without returning anything.

Python creates a function object and binds it to the name you provided. The body of the function is not executed at that moment — it only runs when you call the function by writing its name followed by parentheses.

Yes. Parentheses are still required even when there are no parameters. For example: def greet(): is valid. The parentheses are what Python uses to distinguish the function name from a call.

Defining a function with def stores it in memory but does not run it. Calling a function by writing its name followed by parentheses — such as greet() — actually executes the code inside the function body.

Yes. Python uses indentation to determine what belongs inside the function. Every line inside the function body must be indented consistently, typically by four spaces. Incorrect indentation will cause an IndentationError.

Yes. Python allows nested function definitions. A function defined inside another function is called a nested or inner function. It is only accessible within the outer function's scope unless explicitly returned or passed out.