MOD-02 · Sequence #2 · Python Basics

Python Comments

Comments explain why code was written, while docstrings specify how modules, functions, and classes behave. Docstrings are accessible at runtime via the __doc__ attribute and power automated documentation tools like Sphinx and help().

Live Interactive Code Snippet (Python 3.12 CPython WASM) Open in Practice Mode →
# This is a single line comment
"""
This is a multiline
docstring explaining logic
"""
print("Comments documented")

Core Principles & Mental Models

1. Comments vs. Docstrings

Compile-Time Stripping vs. Runtime Reflection

  • Single-line comments start with a hash symbol (#) and are completely discarded by the Python compiler into bytecode.
  • Docstrings are string literals placed immediately as the first statement of a module, function, class, or method.
  • CPython retains docstrings as bytecode constants and binds them to the object’s `__doc__` special attribute.
def calculate_bmi(weight_kg, height_m):
    """Calculate Body Mass Index.

    Args:
        weight_kg: Weight in kilograms (float)
        height_m: Height in meters (float)

    Returns:
        Calculated BMI value (float)
    """
    return weight_kg / (height_m ** 2)

print(calculate_bmi.__doc__)
💡 Key Takeaway: Docstrings are introspectable at runtime via obj.__doc__ and help(obj), making them essential for reusable software.

Interactive Walkthrough Examples

Function Documentation with Google-style Docstrings (Basic)

Creating accessible documentation for an undergraduate math helper.

def gcd(a: int, b: int) -> int:
    """Compute the Greatest Common Divisor using Euclid's algorithm.
    
    Parameters:
        a (int): First non-negative integer.
        b (int): Second non-negative integer.
        
    Returns:
        int: Greatest common divisor of a and b.
    """
    while b != 0:
        a, b = b, a % b
    return a

print("GCD(48, 18):", gcd(48, 18))
print("First line of docstring:", gcd.__doc__.strip().split("\n")[0])

Explanation: Notice how gcd.__doc__ is preserved and accessible at runtime.

Common Misconceptions & Exam Traps

Common Pitfall: Using Triple Quotes Inside a Function as a Comment Instead of Docstring

If placed after other statements, a triple-quoted string is simply an unassigned expression, not the __doc__ metadata.

Buggy Code
def compute():
    x = 10
    """This is placed AFTER code so it is NOT a docstring,
    it is an unassigned string literal evaluated as a statement!"""
    return x * 2
Correct Solution
def compute():
    """Placed immediately as the first statement."""
    x = 10
    # Use regular # comments for inline explanations
    return x * 2

Exam Trap Note: In exams inspecting `func.__doc__`, misplaced docstrings evaluate to None.

Conceptual Knowledge Self-Check Quiz

Q1: Which special attribute stores a function's docstring at runtime in Python?

  1. __comment__
  2. __help__
  3. __doc__
  4. __meta__

__doc__ holds the string literal placed at the top of the function definition.

Algorithmic Practice Challenges

Idiomatic Best Practices

  • ✅ Write comments to answer "why", not "what" — clear code already shows what it does.
  • ✅ Always start docstrings with a one-line summary followed by a blank line and detailed notes.

All 26 Curriculum Modules