Apps Productivity How-To

How to Define a Function in Python

Use the def keyword to declare a function, add parameters in parentheses, end the header with a colon, and indent the body.

Use the def keyword to declare a function, add parameters in parentheses, end the header with a colon, and indent the body.

Use the official Python tutorial on defining functions as your reference: every function starts with def, followed by a name, parentheses for parameters, a trailing colon, and an indented block that runs when the function is called.

Method 1 — Create and Call a Basic Function

Declare a function with def and a colon.
def greet():
    print("Hello from a function!")
Call the function using its name with parentheses.
greet()

This establishes the minimal pattern: definition first, call after. Python executes top to bottom, so a function must be defined before it’s called.


Method 2 — Add Parameters and Defaults

Add parameters inside the parentheses to accept inputs.
def full_name(first, last):
    print(first + " " + last)
Call the function with matching arguments.
full_name("Ada", "Lovelace")
Assign a default value with = to make an argument optional.
def hello(name="World"):
    print(f"Hello, {name}!")

hello()          # uses default
hello("Python")  # overrides default

Defaults simplify callers and keep your API stable when adding optional behavior. See default arguments in the official tutorial.


Method 3 — Return Values

Use return to send a value back to the caller.
def area(w, h):
    return w * h
Capture the returned value in a variable.
a = area(3, 4)
print(a)
Return multiple values (they’re packed into a tuple).
def point():
    return 10, 20

x, y = point()

Details of the return statement are covered in the language reference.


Method 4 — Accept a Variable Number of Arguments

Collect extra positional arguments with *args.
def total(*args):
    return sum(args)

print(total(1, 2, 3))
Collect keyword arguments with **kwargs.
def report(**kwargs):
    for k, v in kwargs.items():
        print(k, "=", v)

report(name="Keyboard", price=19.99)

This interface lets your function flex to diverse inputs. See “Arbitrary argument lists” in the official tutorial.


Method 5 — Control How Callers Pass Arguments

Make some parameters positional-only by adding / after them.
def echo(x, /):
    print(x)

echo(3)      # OK
# echo(x=3)  # TypeError
Make parameters keyword-only by adding * before them.
def scale(value, *, factor=2):
    return value * factor

scale(10, factor=3)  # OK
# scale(10, 3)       # TypeError

Use these to design clear, safe APIs. See “Special parameters” in the official tutorial.


Method 6 — Document and Organize Your Function

Add a docstring on the first line of the body to describe purpose, parameters, and return value.
def hypotenuse(a, b):
    """Compute the length of the hypotenuse from legs a and b."""
    return (a**2 + b**2) ** 0.5
Guard script-only calls with if __name__ == "__main__" so imports don’t execute them.
def main():
    print(hypotenuse(3, 4))

if __name__ == "__main__":
    main()

Docstring conventions are defined in PEP 257, and the __main__ pattern is covered in the docs on executing modules as scripts.


Method 7 — Use a Lambda for Simple One‑Liners

Create a small anonymous function with lambda for quick, single‑expression cases.
double = lambda x: x * 2
print(double(5))
Prefer def when you need statements, a docstring, or reuse.
def double_def(x):
    return x * 2

Lambda syntax is specified in the language reference.


Method 8 — Place Definitions Where They’ll Be Executed Before Use

Define functions before the first call in the file to avoid name errors.
# Correct: defined before use
def hello():
    print("Hello")

hello()
Avoid calling a function before its definition is executed; Python resolves names at runtime, top to bottom.
# This will raise NameError at runtime:
# hello()
# def hello():
#     print("Hello")
Optionally define helper functions inside another function to keep scope local.
def outer():
    def inner():
        return "scoped helper"
    return inner()

Quick Tips

  • “Parameters” are the names in the function header; “arguments” are the values you pass in the call.
  • Use pass as a placeholder when stubbing a function body.
  • Keep functions small and focused; this simplifies testing and reuse.

With def, thoughtful parameters, and clear returns, you’ll write functions that are easy to call, test, and extend. Start simple, then add defaults, *args/**kwargs, and argument rules as your API needs grow.