AlgoMaster Logo

Comments

Low Priority16 min readUpdated June 6, 2026
Listen to this chapter
Unlock Audio

Code gets read more often than it gets written, and the next person reading yours is usually you, six months later. Comments and docstrings are how Python lets you leave notes for that future reader. This lesson covers the two forms Python supports, when each one is appropriate, and the small set of conventions that keep them useful instead of noisy.

Single-Line Comments with #

Anything from a # to the end of the line is a comment. Python's parser skips it entirely, so it has zero effect on what the program does.

The # can also appear partway through a line. Everything before it runs as code, everything after it is ignored.

Both styles are valid. A comment on its own line usually explains the block of code that follows it. An inline comment annotates a single line, often a variable whose meaning isn't obvious from its name.

A small style detail worth getting right early: PEP 8, the official Python style guide, recommends two spaces between code and the # of an inline comment, then one space after the #. So total = 0 # running cart total, not total = 0 #running cart total. Most editors and formatters apply this automatically.

Python Has No Multi-Line Comment Syntax

If you've used C, Java, or JavaScript, you've seen /* ... */ for block comments that span multiple lines. Python doesn't have anything equivalent. The official way to write a multi-line comment is to start each line with its own #.

You will occasionally see people use a triple-quoted string for the same effect:

That works in the sense that nothing crashes, but it isn't a comment. It's a string literal that gets created and immediately thrown away. The parser still has to read it, and tools that inspect your code will treat it as a string, not a comment. The only place a triple-quoted string has special meaning is as a docstring. Elsewhere, use #.

Triple-Quoted Strings and Docstrings

Python uses triple quotes ("""...""" or '''...''') for strings that span multiple lines. A normal string literal looks like "hello". A triple-quoted one can include line breaks inside it without any escaping:

That's just a regular string. It happens to span three lines.

A docstring is what you get when a triple-quoted string sits at the very top of a module, class, or function. Python treats that string as documentation for the object and attaches it to the object's __doc__ attribute. The built-in help() function reads it.

Three things make that string a docstring rather than a regular string:

  1. It uses triple quotes.
  2. It's the first statement of the function body (no code before it).
  3. It's a bare string with no assignment, no print, nothing else around it.

Move it anywhere else inside the function, and it becomes a useless string literal that Python evaluates and discards. The placement matters.

Where Docstrings Live

A docstring can sit at the top of three places:

LocationWhat it documents
Top of a .py fileThe module
First line inside a class bodyThe class
First line inside a def bodyThe function or method

Here's a module docstring at the top of a file (cart_utils.py):

A class docstring sits right under the class line:

And a function docstring sits right under the def line:

In each case, the docstring is the first statement of the body. Nothing else can come before it, not even a blank line of code.

Accessing Docstrings: __doc__ and help()

Every module, class, and function in Python has a __doc__ attribute. If you wrote a docstring, that's what's stored there. If you didn't, it's None.

cart_total has a docstring, so __doc__ returns the string. shipping_fee doesn't, so __doc__ is None. The function still works fine, it just has no documentation attached.

The help() built-in does something similar but prints a more readable view. In a REPL session:

help() shows the function's signature on one line and the docstring underneath. It works the same way on classes and modules. This is the same machinery that powers the documentation in IDEs, hover tooltips, and Jupyter's ? shortcut. Write a docstring, and your editor knows what your function does.

PEP 257: The Short Version

PEP 257 is the official convention for writing docstrings. It's short, and the rules that matter for everyday code fit in a few bullet points:

  • Use triple double quotes ("""..."""), even when the docstring fits on one line. Triple single quotes work too, but the convention is double.
  • For a one-line docstring, keep the opening and closing quotes on the same line: """Return the sum of cart prices.""".
  • Write the summary as an imperative sentence: "Return the total", not "Returns the total" or "This function returns the total". Think of it as a command to the function.
  • End the summary with a period, even if it's just a phrase.
  • For a multi-line docstring, put the summary on the first line, leave a blank line, then add the longer description.

A one-line docstring:

A multi-line docstring:

Notice that the closing """ of a multi-line docstring goes on its own line. That's a small detail PEP 257 calls out specifically.

Detailed conventions for documenting parameters and return values (the Args:, Returns:, Raises: blocks you may have seen in larger codebases) are part of writing function docstrings well. For now, a clear summary sentence is enough.

When to Comment: Explain the Why, Not the What

The hardest part of writing good comments is knowing when not to write them. A comment that restates what the code already says adds noise. A comment that explains why the code exists adds real information.

Here's a comment that adds nothing:

The code already says that. Anyone reading it can see what's happening. The comment makes the line longer without telling them anything new.

Here's a comment that pulls its weight:

Now the reader knows why this specific number is in the code. If a product manager later asks to change it, the next developer understands the reasoning behind the original choice. That's information you can't get from the variable name alone.

The same principle applies to a non-obvious calculation:

Without the comment, the next developer might "fix" the order by applying the discount first, which would silently change every total in the system. The comment defends the code from well-intentioned changes.

A useful test before adding a comment: "If I rename the variables and clean up the code, does this comment still need to exist?" If clearer code would erase the need for the comment, write the clearer code first. Comments are a backup, not a substitute for readable code.

Avoid Commented-Out Dead Code

This is one of the most common comment anti-patterns:

Three older versions of the same calculation, all commented out. Each was probably correct once. Now they just sit there, taking up space and forcing the reader to wonder whether one of them is the "real" version that should be uncommented.

Commented-out code rots fast. The function signature changes, the variable names drift, the logic moves to a new file, and the commented version no longer matches reality. It becomes a lie the reader has to mentally filter out.

The fix is simple: delete it. Your version control system (Git, for example) remembers every line you ever wrote. If you need the old version back, the history has it. The current file should only contain the code that's actually running.

If a chunk of code is genuinely temporary (a feature flag, an experiment you'll re-enable next week), use a real mechanism for it: a variable, a function parameter, a configuration value. Don't park it in a comment and hope nobody touches it.

The flow above is the decision you make every time you're tempted to leave a block of code commented out. The default answer is to delete.

Putting It Together

Here's a small module that uses all of the pieces this lesson covers: a module docstring, function docstrings, a useful inline comment, and zero dead code.

Every docstring is a one-line or short multi-line summary in the imperative mood. The inline comment explains a small conversion that isn't obvious at a glance. There's no commented-out code. The module docstring tells a new reader what this file is for before they read a single line of logic.

Quiz

Comments Quiz

10 quizzes