Python Defining Functions: Syntax, Parameters, and Return Values
Defining a function in Python means giving a block of code a name so you can run it whenever you need it. A function can accept inputs, do work, and optionally return a result. This article shows how def works, how parameters and return values behave, and the mistakes that catch beginners most often.
Difficulty: Beginner
Helpful to know first: basic Python syntax, variables, and how indentation groups code into blocks.
How Python Function Definitions Work
Use def to create a function. A function definition gives the function a name, a parameter list in parentheses, and a colon. The indented block under it is the function body. Python does not run that body when it reads the definition. It runs the body only when you call the function.
Here is the smallest useful example:
def greet():
print("Hello!")
greet() # Output: Hello!The name is greet. The empty parentheses mean the function takes no inputs. The indented print() runs when you call greet(), not when Python first sees the definition.
A function definition is also a statement. When Python reaches it, it creates a function object and stores it under the given name.
Writing Functions with Parameters and Return Values
Most functions are more useful when they accept inputs. Parameters are the names inside the definition. Arguments are the actual values you pass when you call the function.
Use return when you want the function to send a value back to the caller. If a function reaches the end without return, it returns None.
A function that adds two numbers
This function takes two parameters, adds them, and returns the result. The calling code can store that result in a variable or print it.
def add(a, b):
return a + b
total = add(3, 5)
print(total) # Output: 8The function does not print anything itself. It computes a value and returns it. That makes the function easier to reuse in other calculations.
A function that builds a message
Sometimes a function should return text instead of printing it. That keeps display logic separate from data logic.
def welcome_message(name):
return f"Welcome, {name}!"
message = welcome_message("Ava")
print(message) # Output: Welcome, Ava!This version is better than printing inside the function if you want to reuse the message elsewhere, such as in a file, webpage, or test.
A function with an optional parameter
You can give a parameter a default value. If the caller omits that argument, Python uses the default.
def power(base, exponent=2):
return base ** exponent
print(power(4))
print(power(4, 3)) # Output: 16\n64Default values are useful when a common case should be easy to call, but callers can still override it when needed.
What Happens When Python Reads a Function Definition
Python evaluates a function definition once, at the moment execution reaches it. It does not execute the body right away. It also evaluates default parameter expressions at definition time, not every time the function is called. That detail matters for mutable defaults and other surprising cases.
Function bodies are not run until call time
This example shows that the body does not execute when the function is defined.
def show_start():
print("Function body ran")
print("Before call")
show_start()
print("After call") # Output: Before call\nFunction body ran\nAfter callOnly the call to show_start() runs the indented block.
Default values are created once
If a default value is a mutable object such as a list, Python reuses the same object on each call that omits that argument. That is one of the most important details about defining functions.
def append_item(item, items=[]):
items.append(item)
return items
print(append_item(1))
print(append_item(2)) # Output: [1]\n[1, 2]The second call sees the same list from the first call. This is usually not what you want, so later sections show the correct pattern.
Names inside the function are local
Variables created inside a function usually belong to that function only. They do not automatically replace variables outside the function.
def make_score():
score = 10
return score
print(make_score()) # Output: 10The variable score exists only inside make_score(). That separation helps keep functions predictable.
Worked Examples of Defining Functions in Real Programs
Cleaning up repeated math
If you repeat the same calculation several times, move it into a function. That makes the code shorter and easier to change later.
def celsius_to_fahrenheit(celsius):
return (celsius * 9 / 5) + 32
print(celsius_to_fahrenheit(0))
print(celsius_to_fahrenheit(20)) # Output: 32.0\n68.0The function hides the formula behind a clear name. Anyone reading the call can understand what it does without re-deriving the math.
Validating a value before using it
Functions are a good place to check inputs and raise an error early if something is wrong.
def positive_square_root(number):
if number < 0:
raise ValueError("number must be non-negative")
return number ** 0.5
print(positive_square_root(9)) # Output: 3.0The function protects the rest of the program from invalid input. If the caller passes a negative number, the error happens at the right place.
Returning more than one result
A function can return multiple values as a tuple. This is common when one operation produces related pieces of data.
def split_name(full_name):
parts = full_name.split()
return parts[0], parts[-1]
first, last = split_name("Ada Lovelace")
print(first)
print(last) # Output: Ada\nLovelaceMultiple return values are still one returned object: a tuple. Python lets you unpack that tuple directly into separate variables.
Using a function as a reusable building block
Defining small functions helps larger programs stay readable. Each function should do one job clearly.
def format_username(username):
return username.strip().lower()
def is_valid_username(username):
return len(format_username(username)) >= 3
print(format_username(" Alice "))
print(is_valid_username(" Al ")) # Output: alice\nFalseOne function can call another function. That is normal and often a better choice than making one large function do everything.
Why Default Arguments and Mutable Values Can Surprise You
One of the most common misunderstandings about defining functions is when default values are created. For immutable values like int or str, this usually does not cause trouble. For mutable values like lists and dictionaries, it can produce shared state across calls.
Compare these two patterns:
def bad_log(message, log=[]):
log.append(message)
return log
def good_log(message, log=None):
if log is None:
log = []
log.append(message)
return log
print(bad_log("one"))
print(bad_log("two"))
print(good_log("one"))
print(good_log("two")) # Output: ['one']\n['one', 'two']\n['one']\n['two']The safe version creates a new list inside the function each time the caller does not supply one. That keeps each call independent.
Predict the Output
Does the function change the original list?
What does this print?
def add_item(items):
items.append(3)
numbers = [1, 2]
add_item(numbers)
print(numbers)Show answer
The output is [1, 2, 3]. The function receives a reference to the same list object, so append() changes that object in place. The name numbers still points to the modified list after the call.
What happens with integer division in a function?
What does this print?
def half(value):
return value / 2
print(half(5))Show answer
The output is 2.5. In Python 3, the / operator always performs true division and returns a float, even when both inputs are integers. If you want whole-number division, use // instead.
Find the Bug
Here is a function that looks reasonable but has a subtle bug. Find it before reading the fix.
def add_tag(tag, tags=[]):
tags.append(tag)
return tags
print(add_tag("python"))
print(add_tag("functions"))Show answer
The bug is the mutable default list. Python creates that list once when the function is defined, then reuses it on every call that omits tags. That means the second call sees the list from the first call.
Fixed code:
def add_tag(tag, tags=None):
if tags is None:
tags = []
tags.append(tag)
return tags
print(add_tag("python"))
print(add_tag("functions"))The fixed version works because it creates a fresh list for each call that does not pass one in.
Common Mistakes When Defining Functions
Forgetting the colon after the function header
A function definition must end with a colon. Without it, Python cannot start the indented block correctly.
Problem: The header is incomplete, so Python raises a syntax error before it can create the function.
def hello()
print("Hi")Fix: Add the colon at the end of the header.
def hello():
print("Hi")The colon tells Python that an indented block belongs to the function definition.
Calling the function with too few arguments
If a function requires parameters, the caller must supply them unless defaults exist.
Problem: The call does not provide every required argument, so Python stops with a TypeError.
def area(length, width):
return length * width
print(area(5))Fix: Pass both values, or give one parameter a default if that makes sense for the function.
def area(length, width):
return length * width
print(area(5, 2))The corrected call matches the function’s parameter list, so Python can evaluate it normally.
Using a mutable default argument
This mistake is subtle because the code runs, but the behavior changes across calls.
Problem: The list is shared between calls, so old values stay in the default list and the function does not behave like a fresh start each time.
def collect(item, items=[]):
items.append(item)
return items
print(collect("a"))
print(collect("b"))Fix: Use None as the default, then create a new list inside the function.
def collect(item, items=None):
if items is None:
items = []
items.append(item)
return itemsThe fixed version creates a separate list for each call that needs one.
Returning the wrong thing or nothing at all
Some beginners print a result instead of returning it, then try to use the function as if it produced a value.
Problem: The function prints the answer but returns None, so later code that expects a number gets the wrong value.
def double(n):
print(n * 2)
result = double(4)
print(result)Fix: Return the value, and print it outside the function if needed.
def double(n):
return n * 2
result = double(4)
print(result)The corrected function gives the caller a real result to store, reuse, or print later.
When to Use a Function and When to Use Something Else
Use a function when you need the same logic more than once, when a block of code has one clear job, or when you want to test and reuse the logic separately. Use inline code only when the operation is tiny and does not need a name.
| Choice | Use it when | Example |
|---|---|---|
| def function | You need reusable logic, a return value, or a named action | def calculate_tax(amount): ... |
| Inline code | The operation is one simple step used only once | total = price * 1.2 |
| Built-in function | Python already provides the exact behavior | len(items), print(text) |
Functions are also better than copy-pasting code. Copying creates maintenance problems because you must change every copy by hand.
Interview Questions About Defining Functions
What is the difference between a parameter and an argument?
A parameter is the name in the function definition. An argument is the value passed into the function call. For example, in def greet(name):, name is a parameter, and in greet("Mia"), "Mia" is an argument.
Why would you return a value instead of printing it?
Returning makes the result reusable. The caller can print it, store it, test it, combine it with other values, or ignore it. Printing is for display, not for data flow.
What does a function return if you do not write return?
It returns None. That is Python’s default result for a function that finishes without an explicit return statement.
Try It Yourself
Write a function that formats a book title.
- Define a function named format_title that takes one parameter named title.
- The function should return the title in uppercase.
- Call the function with the string "python basics".
- Print the returned value.
Expected output:
PYTHON BASICSHint: Use the string method upper() inside the function, and remember to return the result.
Show solution
def format_title(title):
return title.upper()
print(format_title("python basics")) # Output: PYTHON BASICSSummary
- Use def to define a function name, parameter list, and indented body.
- A function body runs only when you call the function.
- Use return to send a value back to the caller.
- Parameters are defined in the function; arguments are passed in the call.
- Default values are created when the function is defined, so mutable defaults can cause shared state.
- Print for display, but return values for reuse and testing.
Next, learn about function calls and how Python matches positional arguments, keyword arguments, and default values.