Python Comments & Docstrings: Complete Guide (PEP 8 & PEP 257)

Comments are programmer-written annotations included in source code to explain logic, clarify complex algorithms, and prevent lines of code from executing during debugging. The Python interpreter completely ignores comments during compilation. In this lesson, you will learn how to write clean, professional single-line comments, multi-line blocks, and standardized Docstrings (PEP 257).


1. Single-Line Comments (The # Symbol)

Any text following the hash symbol (#) on a line is treated as a comment:

# This is a full-line comment explaining the variable below
conversion_rate = 83.25  # USD to INR conversion rate (inline comment)

# Best Practice (PEP 8): Separate inline comments with at least 2 spaces!

2. Multi-Line Comments in Python

Unlike C++ or Java which use /* ... */, Python provides two standard ways to comment multiple lines:

Approach A: Multiple Consecutive Hash Characters (Recommended by PEP 8)

# Step 1: Query student records from the database
# Step 2: Calculate total semester grade point average (GPA)
# Step 3: Send automated email notification to student portal

Approach B: Unassigned Triple-Quoted Strings

"""
This multi-line string is not assigned to any variable.
The CPython compiler parses it as a literal, evaluates it,
finds no references to it, and immediately discards it!
"""
print("Application running...")

3. Python Docstrings (Documentation Strings - PEP 257)

A docstring is fundamentally different from a regular comment. When a triple-quoted string appears as the first statement inside a function, class, or module, Python preserves it as the docstring metadata attribute (__doc__):

def calculate_simple_interest(principal: float, rate: float, time: float) -> float:
    """
    Calculate and return the simple interest on a loan.

    Parameters:
        principal (float): The principal investment amount.
        rate (float): Annual interest percentage rate (e.g. 7.5).
        time (float): Time duration in years.

    Returns:
        float: Total interest earned over the given period.
    """
    return (principal * rate * time) / 100

# Accessing the docstring at runtime:
print(calculate_simple_interest.__doc__)

# Python's built-in interactive help system reads docstrings directly:
# help(calculate_simple_interest)

PEP 8 Rules for Writing Professional Comments

• Keep Comments Up to Date: An out-of-date comment that contradicts the code is worse than no comment at all!

• Explain "Why", Not "What": Do not state the obvious. Good comments explain why an algorithm or business rule was chosen, not what the syntax already reveals.

• Complete Sentences: Always start comments with a capital letter and end with a period if it is a complete sentence.


Frequently Asked Questions (FAQ)

Do comments decrease Python program execution speed?

No. Comments are completely stripped away during the tokenization and parsing stage before bytecode is compiled. They have zero impact on program execution speed or memory usage.

How does Sphinx or automated documentation generators work with Python?

Tools like Sphinx, pdoc, and MkDocs inspect module and function __doc__ attributes to automatically generate professional HTML documentation websites for Python libraries.
Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!