Comments & Documentation in Python

Why Use Comments?

Comments clarify why certain code exists or how it works. They help others (and your future self) understand your code.

Single-line Comments

Use the # symbol to add a comment for the rest of the line.

# This is a single-line comment
print("Hello, World!")  # This comment follows code on the same line

Multi-line Comments

Use consecutive # lines or triple quotes (though triple quotes are mainly for docstrings).

# This is a multi-line comment
# explaining the following code block
print("Example")

What are Docstrings?

Docstrings are special string literals used to document modules, classes, methods, and functions.

Example: Function Docstring

def add(a, b):
    """
    Adds two numbers and returns the result.

    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

Example: Accessing Docstrings

print(add.__doc__)

help(add)

Best Practices