Introduction to Computer Science/4.4 Documenting Your Functions with Docstrings

4.4 Documenting Your Functions with Docstrings



🎯 Learning Goals for This Page
  • Explain the purpose of a docstring.
  • Write a multi-line docstring using triple quotes (""").
  • Follow a standard format to describe a function's purpose, parameters, and return value.

Writing Code for Humans

Your code isn't just for the computer. It's also for other programmers, and most importantly, for your future self! Six months from now, you might not remember what a complex function does. To solve this, professional programmers write documentation directly inside their code using docstrings.

A docstring is a multi-line string placed as the very first thing inside a function's definition. Its only job is to explain the function's "contract" with the user.

The Three Parts of a Good Docstring

  1. Purpose: A one-sentence summary of what the function does.
  2. Parameters: A list of all parameters the function accepts, including their expected data type.
  3. Return Value: A description of the value the function returns, including its data type.

The Syntax: Triple Quotes

We create docstrings using triple double-quotes (""") or triple single-quotes (''').

The "Final" Version of Our add_numbers Function

Let's take the function from our last lesson and add a professional docstring. This is now a complete, well-documented, and reusable piece of code.

def add_numbers(num1, num2):
    """Calculates the sum of two numbers.

    Args:
        num1 (int or float): The first number.
        num2 (int or float): The second number.

    Returns:
        int or float: The sum of num1 and num2.
    """
    result = num1 + num2
    return result

# Now, anyone can understand how to use our function without reading the code!
sum_result = add_numbers(10, 5)
print(sum_result)

A Habit for Success

Getting into the habit of writing a docstring for every function you create is one of the most important skills you can build. We will expect all functions in your projects from now on to be documented this way.

Interactive Sandbox

Use this space to practice writing code and complete the "Your Turn" activities above.

Python 3Initializing...
Loading code editor...
Program output will appear here...