The def keyword is how Python creates a function. Once you understand it, you stop writing the same code over and over and start writing programs that are organized, readable, and reusable.
Before def, beginners tend to write the same block of code in multiple places. When something needs to change, they have to hunt down every copy. Functions solve this. You write the logic once, give it a name, and call that name whenever the logic is needed. This tutorial covers the full picture: syntax, parameters, return values, default arguments, and the common mistakes beginners make on the first try.
What def Does and Why You Need It
The word def is short for "define." Writing def followed by a name tells Python to store the block of code underneath it and associate it with that name. The code does not run when Python reads the def line — it only runs when you call the function by name later.
Here is the simplest possible function. It takes no input and produces no output other than printing a message to the screen.
def say_hello():
print("Hello from my first function!")
say_hello() # calling the function
# Output: Hello from my first function!
Three things to notice: the def keyword comes first, the function name is followed by parentheses and a colon, and the body is indented by exactly four spaces. Every line of the function body must share that same indentation level. If the indentation is inconsistent, Python raises an IndentationError.
Function names follow the same rules as variable names. Use lowercase letters, numbers (not at the start), and underscores. Names like calculate_total or get_user_age are readable and follow Python convention (PEP 8).
Build a valid function definition that prints "Ready!" — put the tokens in the right order:
def statement requires: the keyword def, then the function name (launch), then parentheses (), then a colon :. The body (print("Ready!")) goes on the next indented line — it is not part of the def line itself. The return keyword and the extra pipe are distractors not needed here.
Parameters, Arguments, and Return Values
A function with no parameters is useful, but functions become powerful when they can accept input. A parameter is the placeholder name written inside the parentheses of the def line. An argument is the actual value you supply when calling the function.
def greet(name): # name is the parameter
print("Hello, " + name)
greet("Kandi") # "Kandi" is the argument
# Output: Hello, Kandi
When Python runs greet("Kandi"), it assigns the string "Kandi" to the name name and then executes the body. The parameter exists only inside the function — this is called local scope.
Functions can also send a value back to the caller using the return statement. Without return, Python returns None automatically.
def add(x, y):
result = x + y
return result
total = add(10, 5)
print(total) # Output: 15
Once Python reaches a return statement, the function stops immediately. Any code written after return in the same block is unreachable and will never run. Use this intentionally to exit a function early based on a condition.
You can pass more than one argument by separating parameters with commas in the def line. When calling the function, arguments are matched to parameters in the same left-to-right order — these are called positional arguments.
This function is supposed to multiply two numbers and return the result. One line contains a bug. Click it, then hit check.
return to return product. A bare return statement with no value sends back None. The variable product holds the result of the multiplication, so it must be passed to return explicitly.
Default Values and Multiple Returns
Python lets you assign a default value to a parameter in the def line. If the caller does not pass an argument for that parameter, the default is used automatically. Parameters with defaults must always appear after parameters without defaults.
def greet(name, greeting="Hello"):
return greeting + ", " + name + "!"
print(greet("Kandi")) # Hello, Kandi!
print(greet("Kandi", "Welcome")) # Welcome, Kandi!
A function can return more than one value by separating values after return with a comma. Python packages them into a tuple. On the receiving side, you can unpack that tuple into separate variables.
def min_max(numbers):
return min(numbers), max(numbers)
lowest, highest = min_max([3, 1, 7, 2, 9])
print(lowest) # 1
print(highest) # 9
Avoid using a mutable object — such as a list or dictionary — as a default parameter value. Python creates the default object once when the def line is evaluated, not each time the function is called. If you modify it inside the function, the change persists across calls. Use None as the default and create the object inside the body instead.
- Example
def say_hi(): print("Hi")- Use when
- The function performs a side effect (printing, writing a file) and does not need to send data back to the caller.
- Example
def add(x, y): return x + y- Use when
- The function transforms input into a result that the caller needs for further processing. This is the pattern used in most utility and calculation functions.
- Example
def greet(name, greeting="Hello"): return greeting + ", " + name- Use when
- The function has a sensible default for one or more arguments, making it flexible without requiring the caller to always specify every value.
- Example
def stats(nums): return min(nums), max(nums)- Use when
- The function naturally produces two or more related results. Python packs them into a tuple. The caller can unpack the tuple or treat it as a single object.
"A function should do one thing, and do it well." — Unix design philosophy, widely cited in software engineering
How to Define and Call a Function in Python
Follow these steps to write and use your first Python function from scratch.
-
Write the def line
Type
deffollowed by a descriptive name for your function, then open and close parentheses, and end the line with a colon. For example:def greet(): -
Add the function body
Indent the next line by four spaces and write the code the function should run. For example:
print("Hello!"). Every line in the body must share this indentation level. -
Add a parameter
Place a variable name inside the parentheses to accept input when the function is called:
def greet(name):. Use that variable anywhere inside the body. -
Add a return statement
If the function should produce a value for the caller to use, add
returnfollowed by that value:return "Hello, " + name. If you only need a side effect like printing, you can skipreturn. -
Call the function
After the function definition, call it by writing the name followed by parentheses and any required arguments:
result = greet("Kandi"). You can then use or printresult.
Python Learning Summary Points
- The
defkeyword defines a function. The function does not run until it is called by name. - The function name is followed by parentheses and a colon. The body must be indented by four spaces.
- Parameters are placeholders in the
defline. Arguments are the actual values passed when calling the function. - A bare
returnstatement — or noreturnat all — causes the function to returnNone. - Default parameter values make arguments optional at call time. Mutable defaults (lists, dicts) should be avoided — use
Noneinstead. - A function can return multiple values separated by commas; Python wraps them in a tuple automatically.
Functions are the foundation of every Python program larger than a few lines. Learning to define and call them cleanly — with well-chosen names, clear parameters, and explicit return values — is one of the most important skills to build early. Practice by taking any repeated block of code you have written and converting it into a named function.
Frequently Asked Questions
def is a keyword in Python that signals the start of a function definition. It tells the interpreter that you are creating a reusable block of code with a name, optional parameters, and an optional return value.
The syntax is: def function_name(parameters): followed by an indented block of code. The colon after the parentheses and the indentation are both required. For example: def greet(name): print("Hello, " + name)
No. A Python function that has no return statement, or that reaches the end of its body without one, automatically returns None. Use return only when you need the function to send a value back to the caller.
A parameter is the variable name listed inside the parentheses of a def statement. An argument is the actual value you pass when you call the function. In def add(x, y), x and y are parameters. When you call add(3, 5), the values 3 and 5 are arguments.
Yes. A function with no parameters is written with empty parentheses: def say_hello(): The parentheses are still required even when there are no parameters.
Default values are fallback values assigned to a parameter in the def line using an equals sign. For example: def greet(name='World'): means that if no argument is passed, name will be 'World'. Parameters with defaults must come after parameters without defaults.
Python uses indentation instead of curly braces to define code blocks. Every statement inside a function must be indented by the same amount — typically four spaces. Inconsistent indentation causes an IndentationError.
Python will raise a NameError because the function name is not yet defined at the point the call is made. Function definitions must appear before the call in the file, unless the call itself is inside a function that is only executed after all definitions are loaded.
Yes. When you write return a, b, Python packages the values into a tuple and returns that single tuple. You can unpack it on the calling side: x, y = my_function()
A docstring is a string literal placed immediately after the def line, inside triple quotes, that describes what the function does. Beginners are encouraged to write them from the start. They are accessible via help() and are the foundation of good documentation habits.