Fundamentals 9 min read

How to Write Effective Comments and Docstrings for Python Functions

This article explains the importance of good comments and docstrings in Python, describes the basic syntax for single‑line, multi‑line, and docstring comments, and provides ten practical examples illustrating various annotation techniques and their typical use cases.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
How to Write Effective Comments and Docstrings for Python Functions

Introduction – Good comments improve code readability and maintainability; Python offers several ways to annotate functions, with docstrings being the most common. Proper commenting and docstrings can greatly enhance understanding for other developers and future maintenance.

Part 1: Overview – Python comments are ignored by the interpreter and come in two main forms: single‑line comments using # and multi‑line comments using triple‑quoted strings (""" ... """) which serve as docstrings. A typical docstring structure includes a brief description, parameter list, and return value description.

Basic syntax example:

def function_name(parameters):
    """
    Docstring
    Parameters:
        parameter1 (type): description
        parameter2 (type): description
    Returns:
        type: description
    """
    # function body
    return result

Part 2: Use Cases and Examples

Example 1: Basic function comment

def add_numbers(a, b):
    """
    Calculate the sum of two numbers
    Parameters:
        a (int or float): first number
        b (int or float): second number
    Returns:
        int or float: sum of a and b
    """
    return a + b

print("Sum:", add_numbers(3, 5))

Use case – provides a clear description of the function’s purpose.

Example 2: Single‑line comment

def calculate_area(radius):
    # Calculate the area of a circle
    import math
    return math.pi * radius ** 2

print("Area:", calculate_area(4))

Use case – brief inline explanation for simple logic.

Example 3: Multi‑line comment

def process_data(data):
    """
    Process a dataset
    Steps:
    1. Clean data
    2. Analyze data
    3. Output results
    """
    cleaned_data = [x for x in data if x is not None]  # Clean data
    analysis_result = sum(cleaned_data) / len(cleaned_data)  # Analyze data
    print("Result:", analysis_result)  # Output result
    process_data([10, 20, None, 30])

Use case – detailed explanation of a complex function.

Example 4: Parameter and return description

def find_max(numbers):
    """
    Find the maximum value in a list
    Parameters:
        numbers (list of int or float): list of numbers
    Returns:
        int or float: maximum value
    """
    return max(numbers)

print("Max:", find_max([1, 3, 5, 7]))

Use case – clarifies expected input and output types.

Example 5: Conditional comment

def check_even_or_odd(number):
    """
    Determine if a number is even or odd
    Parameters:
        number (int): the number to check
    Returns:
        str: "偶数" or "奇数"
    """
    if number % 2 == 0:
        return "偶数"  # Even number
    else:
        return "奇数"  # Odd number

print("Result:", check_even_or_odd(8))

Use case – explains branching logic.

Example 6: Loop comment

def sum_of_squares(n):
    """
    Compute the sum of squares of the first n natural numbers
    Parameters:
        n (int): number of natural numbers
    Returns:
        int: sum of squares
    """
    total = 0
    for i in range(1, n + 1):
        total += i ** 2  # Add square of i
    return total

print("Sum of squares:", sum_of_squares(5))

Use case – clarifies loop operation.

Example 7: Exception handling comment

def divide_numbers(a, b):
    """
    Safely divide two numbers
    Parameters:
        a (int or float): dividend
        b (int or float): divisor
    Returns:
        float: quotient
    Raises:
        ValueError: if divisor is zero
    """
    try:
        return a / b  # Attempt division
    except ZeroDivisionError:
        raise ValueError("Divisor cannot be zero")

print("Quotient:", divide_numbers(10, 2))

Use case – demonstrates robust error handling.

Example 8: Default parameter comment

def greet_user(name="访客"):
    """
    Greet a user
    Parameters:
        name (str): user name, default is "访客"
    """
    print(f"欢迎你, {name}!")

greet_user()

greet_user("张三")

Use case – shows how default arguments work.

Example 9: *args and **kwargs comment

def concatenate_strings(*args, separator=", "):
    """
    Concatenate multiple strings
    Parameters:
        *args (str): strings to join
        separator (str): separator, default ", "
    Returns:
        str: concatenated string
    """
    return separator.join(args)

print("Result:", concatenate_strings("苹果", "香蕉", "橙子"))

Use case – explains variable‑length arguments.

Example 10: Docstring help

def calculate_factorial(n):
    """
    Compute factorial of n
    Parameters:
        n (int): non‑negative integer
    Returns:
        int: n!
    """
    if n == 0:
        return 1
    else:
        return n * calculate_factorial(n - 1)

help(calculate_factorial)
print("Factorial:", calculate_factorial(5))

Use case – using help() to view docstrings.

Conclusion – By following these examples, readers learn how to add clear, concise, and standardized comments and docstrings to Python functions, improving code readability, maintainability, and collaboration while adhering to PEP 257 guidelines.

PythonProgrammingBest Practicescode commentsdocstring
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.