Skip to content

Python Functions

Defining functions with def, parameters, return values, and default arguments.

What you'll learn

  • How to define a function with def
  • Parameters, arguments, and return values
  • Default arguments and keyword arguments
  • Variable-length arguments with *args and **kwargs
  • Docstrings and why you should write them

Concept

Defining a Function

Use the def keyword to define a function, followed by the name, parameters in parentheses, and a colon. The body is indented:

def greet(name):
    return f"Hello, {name}!"

print(greet("Ada"))  # Hello, Ada!

Parameters and Return Values

Functions accept parameters (inputs) and can return a value. If you do not include a return statement, the function returns None:

def add(a, b):
    return a + b

result = add(3, 4)  # 7

Default Arguments

You can give parameters default values, making them optional:

def greet(name, greeting="Hello"):
    return f"{greeting}, {name}!"

greet("Ada")              # Hello, Ada!
greet("Ada", "Hi")        # Hi, Ada!
greet("Ada", greeting="Hey")  # keyword argument

Warning: never use a mutable object (like a list) as a default argument. Default values are evaluated once when the function is defined, so the same list is shared across all calls:

# BAD — the list is shared across calls!
def add_item(item, items=[]):
    items.append(item)
    return items

# GOOD — create a new list each call
def add_item(item, items=None):
    if items is None:
        items = []
    items.append(item)
    return items

Keyword Arguments

You can pass arguments by name, which makes calls more readable and lets you skip optional parameters:

def create_user(name, age, role="user", active=True):
    return {"name": name, "age": age, "role": role, "active": active}

create_user("Ada", 25, role="admin", active=False)

*args and **kwargs

  • ***args** collects extra positional arguments into a tuple
  • kwargs** collects extra keyword arguments into a dict
def sum_all(*args):
    return sum(args)

sum_all(1, 2, 3, 4)  # 10

def log(**kwargs):
    for key, value in kwargs.items():
        print(f"{key} = {value}")

log(user="Ada", action="login", time="10:30")

Docstrings

A docstring is a triple-quoted string at the start of a function that documents what it does. It is accessible via help() and is essential for readable code:

def calculate_bmi(weight, height):
    """Calculate Body Mass Index.

    Args:
        weight: weight in kilograms
        height: height in meters

    Returns:
        The BMI value (weight / height^2)
    """
    return weight / (height ** 2)

Good docstrings explain the why, not just the what. Tools like Sphinx and IDEs use them to provide inline help.

Example

              # Basic function with a return value
def greet(name, greeting="Hello"):
    """Return a greeting message."""
    return f"{greeting}, {name}!"

print(greet("Ada"))
print(greet("Ada", greeting="Hi"))

# A function with multiple returns
def grade(score):
    """Convert a numeric score to a letter grade."""
    if score >= 90:
        return "A"
    elif score >= 80:
        return "B"
    elif score >= 70:
        return "C"
    else:
        return "F"

print(f"Score 85 earns: {grade(85)}")

# *args for variable positional arguments
def sum_all(*args):
    """Sum any number of arguments."""
    return sum(args)

print(sum_all(1, 2, 3, 4, 5))  # 15

# **kwargs for variable keyword arguments
def make_profile(**kwargs):
    """Build a user profile from keyword arguments."""
    return kwargs

profile = make_profile(name="Ada", age=25, role="admin")
print(profile)

# Safe default argument pattern (avoid mutable defaults!)
def add_item(item, items=None):
    """Add an item to a list, creating a new list if none provided."""
    if items is None:
        items = []
    items.append(item)
    return items

print(add_item("a"))        # ['a']
print(add_item("b"))        # ['b'] — not ['a', 'b']!
            

Shows a function with defaults, a multi-return grade function, *args, **kwargs, and the safe pattern for mutable default arguments. The docstrings show how to document functions.

Try it

  • Math Evaluator

    Evaluate expressions — similar to what a function computes and returns.

  • Regex Tester

    Functions often wrap regex logic — test patterns live.

Common mistakes

The mistake

Using a mutable default argument like def f(items=[])

The fix

Default arguments are evaluated once at definition time, so the same list is shared across all calls. Use def f(items=None): items = items or [] to create a fresh list each call.

The mistake

Forgetting to return a value and getting None

The fix

A function without an explicit return statement returns None. If your function should produce a value, make sure to write return value. This is a common source of NoneType errors.

Related Snippets

Related Cheatsheets

Practice Python Functions

2 exercises

Practice Python Functions

Look up unfamiliar terms

A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.

View glossary

Build real projects

Apply what you learned by building guided projects with starter code and solutions.

View projects

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors