Script Valley
Python: Complete Language Course
Functions and Functional PatternsLesson 3.1

How to define and call functions in Python

def keyword, parameters vs arguments, return statement, default parameters, keyword arguments, multiple return values, docstrings

Defining Functions

Functions let you name and reuse a block of code. Define with def, call by name, and use return to send a value back. A function without return implicitly returns None.

def greet(name, greeting="Hello"):
    """Return a greeting string for name."""
    return f"{greeting}, {name}!"

print(greet("Alice"))            # Hello, Alice!
print(greet("Bob", "Hi"))       # Hi, Bob!
print(greet(greeting="Hey", name="Eve"))  # keyword args

Multiple Return Values

def min_max(numbers):
    return min(numbers), max(numbers)

lo, hi = min_max([3, 1, 9, 2])
print(lo, hi)  # 1 9

Docstrings

A docstring is a string literal as the first statement in a function body. It documents purpose, parameters, and return value. Access it with help(func) or func.__doc__. Write docstrings for any function that is not immediately obvious from the name alone. Default parameter values are evaluated once at definition time โ€” never use mutable defaults like [] or {}.

def broken(items=[]):
    items.append(1)
    return items

broken()  # [1]
broken()  # [1, 1]  โ€” shared across calls!

Functions are the primary unit of code reuse and organisation in Python. A well-named function is self-documenting โ€” the name explains what it does and the caller does not need to read the body. Keep functions focused on a single responsibility: if a function does two distinct things, split it. The convention for private helper functions is to prefix with a single underscore: _helper(). Arguments passed to functions are passed by object reference โ€” mutable objects like lists can be modified inside the function, which is sometimes intentional but often a surprise.

Up next

Python *args and **kwargs explained

Sign in to track progress

How to define and call functions in Python โ€” Functions and Functional Patterns โ€” Python: Complete Language Course โ€” Script Valley โ€” Script Valley