Single Line, Inline and Multiline Comments in Python: Complete Code Documentation and Best Practices Guide

Single line, inline and multiline comments in python

I still remember debugging a 400-line script I’d written three weeks earlier with zero comments in it. I had no idea why I’d written half the conditions the way I did. That painful afternoon taught me that comments aren’t optional decoration — they’re a survival tool for anyone who writes code that they, or someone else, will have to read again later.

Comments in Python are lines of text that the interpreter completely ignores during execution. They exist purely for humans. Unlike docstrings, which get stored as retrievable __doc__ attributes, comments vanish the moment the parser tokenizes your source file. Understanding exactly how and when to use them is a small skill that pays off constantly.

The Basics: How Python Recognizes Comments

Python uses the hash symbol # to mark the start of a comment. Everything from that # to the end of the physical line is ignored by the interpreter.

# This entire line is a comment and does nothing when the file runs
print("Hello, world!")  # This part after the code is also a comment

Output:

Hello, world!

Python has no native multi-line comment syntax like /* ... */ in C or Java. This surprises a lot of newcomers coming from other languages, and I’ll explain the common workarounds shortly.

Single-Line Comments

A single-line comment occupies its own line, typically explaining the logic of the code that follows it.

# Calculate the discounted price for a customer
discount_rate = 0.15
price = 200
final_price = price - (price * discount_rate)
print(final_price)

Output:

170.0

I use single-line comments to explain why something is happening, not what is happening — the code itself already shows what it does. A comment like # add 1 to x above x = x + 1 is useless noise. A comment like # offset by 1 to account for zero-indexed API response actually adds information the code alone can’t convey.

Inline Comments

An inline comment sits on the same line as a piece of code, usually separated by at least two spaces, following PEP 8’s style recommendation.

tax_rate = 0.075  # Standard sales tax rate for this region
inventory_count = 42  # Updated manually after last stock audit

I reserve inline comments for short clarifications — a single sentence, at most. If I find myself writing a long inline comment that wraps awkwardly, I move it to its own line above the code instead.

# Bad: cramped and hard to read
total = subtotal * 1.075  # apply the standard regional sales tax rate that changes quarterly based on state regulations

# Better:
# Apply the standard regional sales tax rate.
# Note: this rate is reviewed quarterly per state regulations.
total = subtotal * 1.075

Multiline Comments (The Workarounds)

Since Python doesn’t have a dedicated multi-line comment syntax, there are two common approaches I use depending on the situation.

Approach 1: Consecutive single-line comments

This is the officially recommended and most Pythonic approach.

# This function processes raw sensor data from the temperature module.
# It filters out any readings that fall outside the calibrated range,
# then returns a cleaned list ready for statistical analysis.
def clean_sensor_data(readings):
    return [r for r in readings if -40 <= r <= 125]

Approach 2: Triple-quoted strings used as a comment block

Technically these are string literals, not comments, but many developers (myself included, occasionally) use triple-quoted strings to temporarily block out code during testing.

"""
The block below is disabled while I debug the new pricing engine.
result = calculate_advanced_pricing(order)
apply_discount(result)
"""
print("Testing simplified logic instead")

I want to be honest about a caveat here: this only behaves like a “comment” when the triple-quoted string appears as a standalone statement, in which case Python evaluates it as an unused expression and discards the result. It still gets parsed and briefly created as a string object at runtime, unlike a true # comment, so it’s not zero-cost the way real comments are. For actually documenting a module, class, or function, that same triple-quoted block at the very top is a docstring, not a comment — a subtly different concept.

How the Python Tokenizer Handles Comments Internally

I found it genuinely useful to understand what happens under the hood. When Python’s tokenizer processes your source file, it scans character by character. The moment it encounters a # that isn’t inside a string literal, it treats everything until the next newline as a COMMENT token type and simply discards it before the parser ever builds an abstract syntax tree (AST) from your code.

You can actually observe this using the tokenize module:

import tokenize
import io

code = "x = 5  # assign five to x\n"
tokens = tokenize.generate_tokens(io.StringIO(code).readline)
for tok in tokens:
    print(tok)

Output (trimmed for clarity):

TokenInfo(type=NAME, string='x', ...)
TokenInfo(type=OP, string='=', ...)
TokenInfo(type=NUMBER, string='5', ...)
TokenInfo(type=COMMENT, string='# assign five to x', ...)
TokenInfo(type=NEWLINE, string='\n', ...)

Notice the comment does get tokenized — it’s not invisible to the tokenizer — but it never becomes part of the AST that the compiler turns into bytecode. That’s why comments have zero runtime performance impact: they simply don’t exist by the time your code actually executes.

Comments Inside Strings — A Common Gotcha

The # symbol only starts a comment when it’s outside of a string literal. Beginners sometimes get confused by this:

message = "Use the # symbol to tag hashtags"  # This IS a valid string, not a comment
print(message)

Output:

Use the # symbol to tag hashtags

The interpreter is smart enough to recognize that the # inside the quotes is just a character in a string, not the start of a comment.

Practical Use Cases

Commenting out code during debugging

# result = expensive_api_call(data)   # disabled temporarily to avoid rate limits
result = mock_api_response(data)

Marking TODOs for future work

# TODO: replace this linear search with a hash-based lookup for performance
def find_user(users, user_id):
    for user in users:
        if user["id"] == user_id:
            return user

Many editors, including VS Code and PyCharm, automatically highlight TODO, FIXME, and NOTE comments and let you jump between them, which makes this a genuinely useful workflow habit rather than just a stylistic choice.

Explaining non-obvious logic in automation scripts

# Sleep briefly to respect the API's rate limit of 5 requests per second
time.sleep(0.2)

Section dividers in longer scripts

# -----------------------------
# Configuration
# -----------------------------
API_KEY = "your-key-here"
TIMEOUT = 30

# -----------------------------
# Core logic
# -----------------------------
def fetch_data():
    pass

Best Practices

  • Write comments that explain why, not what — the code already says what it does.
  • Keep comments up to date. A comment that no longer matches the code is more dangerous than no comment at all, because it actively misleads the next reader.
  • Don’t over-comment obvious code. x = x + 1 # increment x adds nothing.
  • Use consistent spacing: PEP 8 recommends at least two spaces before an inline comment, and a single space after the #.
  • Use complete sentences with proper capitalization for comments meant to be read by teammates on shared projects.

Common Mistakes to Avoid

A mistake I see often, and made myself, is leaving large blocks of commented-out dead code sitting in a file indefinitely. If you’re using version control like Git, you don’t need to keep old code around as comments — delete it, since Git history preserves it if you ever need it back.

# Old version, kept "just in case"
# def calculate_total(items):
#     total = 0
#     for item in items:
#         total += item.price
#     return total

def calculate_total(items):
    return sum(item.price for item in items)

That commented-out block just adds clutter. Trust your version control system instead.

FAQs

Does Python have real multi-line comments like /* */? No. Python only has single-line # comments. Triple-quoted strings are sometimes used as a substitute, but they’re technically string literals, not comments.

Do comments slow down my program? No. Comments are discarded during tokenization, before the AST or bytecode is generated, so they add no runtime overhead.

What’s the difference between a comment and a docstring? A comment is always discarded and never accessible at runtime. A docstring is a string literal placed as the first statement in a module, function, or class, and Python stores it in __doc__ so it can be retrieved later.

How much should I comment my code? Enough to explain intent and non-obvious decisions, not so much that the comments outnumber and obscure the actual logic.

Summary

Comments are one of the smallest features in Python syntactically, but one of the most impactful habits in practice. Single-line comments explain a block of logic, inline comments clarify a specific line, and consecutive # lines serve as Python’s answer to multi-line comments. They cost nothing at runtime since they’re stripped out during tokenization, long before your code compiles to bytecode. Used well, they turn code you write today into code you — or someone else — can actually understand months from now.

References

  • Python official style guide (PEP 8) on comments: https://peps.python.org/pep-0008/#comments
  • Python tokenize module documentation: https://docs.python.org/3/library/tokenize.html
  • Python tutorial, general syntax overview: https://docs.python.org/3/tutorial/

Total
0
Shares

Leave a Reply

Previous Post
How Indentation is Parsed in python

How Indentation Is Parsed in Python: Complete Block Structure and Code Formatting Implementation Guide

Next Post
Write documentation using docstrings in python

Write Documentation Using Docstrings in Python: Complete Function, Class, and Module Documentation Guide

Related Posts