Guide Python Beginner

4.5 Comments

Single-line comments, why Python has no dedicated multi-line comment syntax, docstrings and the __doc__ attribute, and best practices for commenting code.

2 min read

Single-line Comments

What Is It?

Text starting with # that the interpreter ignores completely, running to the end of the line.

Why Is It Used?

To explain WHY code does something, for humans reading it later — not to restate what’s already obvious from the code.

# Retry 3 times because the API occasionally times out under load
for attempt in range(3):
    ...

Multi-line Comments

What Is It?

Python has no dedicated multi-line comment syntax — the convention is either a # on every line, or (informally) a triple-quoted string that isn’t assigned to anything, which is technically a string literal statement that gets evaluated and discarded.

# This is a multi-line comment
# written the conventional way,
# one # per line.

Docstrings

What Is It?

A triple-quoted string as the FIRST statement in a module, class, or function — unlike an ordinary comment, it’s stored as the object’s __doc__ attribute and is retrievable at runtime.

Why Is It Used?

Tools like help() and IDEs display it automatically, and doc generators like Sphinx extract it to build reference documentation.

def add(a, b):
    """Return the sum of a and b."""
    return a + b

>>> add.__doc__
'Return the sum of a and b.'

Best Practices

  • Comment the WHY, not the WHAT — the code already shows what it does
  • Keep comments up to date — a stale comment that contradicts the code is worse than no comment
  • Use docstrings for anything meant to be imported/reused by others

Quick Interview Answer

“A # starts a single-line comment running to end of line. Python has no dedicated multi-line comment block — the convention is one # per line. A docstring is different from a comment: it’s a triple-quoted string as the first statement in a module/class/function, stored in __doc__ and retrievable at runtime via help().”

Common Mistakes

  • Confusing a docstring with a regular comment — a docstring must be the first statement in the function/class/module to be picked up as __doc__.
  • Writing comments that restate the code line-for-line instead of explaining a non-obvious reason.
  • Letting a comment go stale after the code beneath it changes.

Add More Questions to This Guide

Know a question that should be here? Share it and help the community!

Open Google Form