Python Comments - Single-Line, Multi-Line & Docstrings

Every programmer, at some point, writes notes within their code. These notes don’t affect the program's logic but help humans understand the why behind the code. These notes are called comments.

Python supports comments through the # symbol for single-line comments and a few different strategies for writing multi-line or documentation comments.

Single-Line Comments in Python

Use the # symbol to start a comment. Everything after # on that line is ignored by Python.

# This is a single-line comment
print("Hello, world!")  # This prints a greeting

Multi-Line Comments

Python doesn’t have a dedicated multi-line comment block like /* */ in some other languages. But you can achieve the same effect using consecutive # symbols or by using multi-line strings (though these are technically not comments).

Approach 1: Using # on each line

# This is a comment
# that spans across
# multiple lines
print("Multi-line comment above!")
Multi-line comment above!

Approach 2: Using Triple-Quoted Strings

Python lets you write multi-line strings using triple quotes (''' or """). If these strings are not assigned to a variable or used in any expression, they are ignored like comments.

"""
This is a multi-line string.
It's often used for docstrings, but
can serve as a multi-line comment if left unused.
"""
print("Triple-quoted string used as comment.")
Triple-quoted string used as comment.

Docstrings (Documentation Strings)

Docstrings are special types of comments used to describe functions, classes, or modules. They are written as the first statement in a function or class using triple quotes.

def greet():
    """This function prints a simple greeting."""
    print("Hello there!")

To see the docstring, use the built-in help() function:

help(greet)
Help on function greet in module __main__:

greet()
    This function prints a simple greeting.

Do’s and Don’ts for Comments

  • Do: Use comments to clarify why something is done, not what is done (code already shows what)
  • Do: Keep comments up-to-date when changing logic
  • Don’t: Leave outdated or misleading comments
  • Don’t: Comment every line unnecessarily

Tip

Comments may seem optional at the beginning, but they are foundational to writing professional, maintainable Python code. Start using them from day one, and your future self will thank you.