Advertisement
🌱 Beginner

Python Comments – Single Line, Multi-line, and Docstrings

Comments are lines in your code that Python ignores — they exist solely for humans to read. Good comments explain the WHY behind code, document complex logic, and make codebases maintainable by teams. This lesson covers all comment types in Python and teaches you when to write them.

⏱️ 12 min read 🎯 Beginner 📅 Updated 2026

Single-Line Comments

Any text after a # symbol on a line is a comment. Python ignores everything from the # to the end of that line.

Python
# This is a full-line comment
print("Hello")  # This is an inline comment

# Multiple single-line comments:
# Step 1: Get user input
# Step 2: Validate it  
# Step 3: Process it
▶ Output
Hello

Multi-Line Comments (Triple Quotes)

Python doesn't have a dedicated multi-line comment syntax. The convention is to use triple-quoted strings (they are technically string literals that get assigned to nothing, so Python ignores them).

Python
"""
This is a multi-line
"comment" using triple quotes.
Python evaluates it as a string but discards it.
"""

print("Code continues here")
▶ Output
Code continues here
Advertisement

Docstrings – Documentation Strings

Docstrings are triple-quoted strings placed as the first statement in functions, classes, or modules. Unlike regular comments, docstrings are accessible at runtime via .__doc__ and are used by documentation generators.

Python
def calculate_area(radius):
    """
    Calculate the area of a circle.

    Args:
        radius (float): The radius of the circle.

    Returns:
        float: The area of the circle.
    """
    import math
    return math.pi * radius ** 2

print(calculate_area(5))
print(calculate_area.__doc__)
▶ Output
78.53981633974483 Calculate the area of a circle. ...

When to Write Comments – Best Practices

Comments should explain WHY, not WHAT. Well-named code explains itself. Only add comments when the reasoning is not obvious.

Python
# ❌ Useless comment - the code already says this
x = x + 1  # increment x by 1

# ✅ Useful comment - explains non-obvious behavior
x = x + 1  # Offset by 1 to convert 0-based index to 1-based display

# ✅ Useful: explains a workaround
# Using int() instead of round() here because the legacy API
# expects truncated values, not rounded (see ticket #1234)
result = int(value)
💡
Tip

The best code requires no comments because variable and function names make the intent clear. Aim for self-documenting code first, comments second.

Comments: Explain Why, Not What

Python ignores everything after # on a line. But good comments don't repeat the code — they explain the reasoning the code can't show. A comment restating the obvious is noise; one capturing a decision is gold.

x = x + 1          # ❌ "add one to x" — the code already says this
retries = 3        # ✅ vendor API rate-limits after 3 rapid calls

# TODO: replace with pagination once the endpoint supports it
data = fetch_all()
TypeSyntaxUse
Inline / block# ...explain intent
Docstring"""...""" first line of def/classdocument API (readable via help())

Key distinction: a # comment is stripped and invisible at runtime; a docstring (a string literal as the first statement in a function, class, or module) is stored on the object and shown by help() and IDE tooltips. Document public functions with docstrings, use # for in-line reasoning, and delete commented-out code — that's what version control is for.

🏋️ Practical Exercise

Practice every comment style:

  1. Write a script with a single-line # comment explaining what it does.
  2. Add a multi-line explanation using triple quotes.
  3. Write a function and give it a proper docstring describing its purpose, arguments, and return value.
  4. Access and print that function’s docstring with function_name.__doc__.

🔥 Challenge Exercise

Take a short, uncommented function you have written before (e.g. a temperature converter) and document it fully: add a one-line summary docstring, document each parameter and the return value, and add inline comments only where the logic is non-obvious. Then deliberately remove a redundant comment like # add 1 to x to practice recognizing comments that add no value.

📋 Summary

  • Single-line comments start with # and run to the end of the line.
  • Python has no dedicated multi-line comment syntax; triple-quoted strings are commonly used for block notes.
  • Docstrings are triple-quoted strings placed as the first statement of a module, function, or class.
  • Docstrings are accessible at runtime through the __doc__ attribute and power help().
  • Good comments explain why, not what — the code already shows what it does.
  • PEP 8 and PEP 257 give the conventions for comments and docstrings.

Interview Questions on Comments

  • How do you write a single-line comment in Python?
  • Does Python have true multi-line comment syntax?
  • What is a docstring and how is it different from a regular comment?
  • How do you access a function’s docstring at runtime?
  • What is the difference between # comments and triple-quoted strings?
  • What does PEP 257 cover?
  • When should you avoid writing a comment?

FAQ

Does Python have a real multi-line comment like /* */? +

No. Python only has the # single-line comment. To comment several lines you either prefix each with # or use a triple-quoted string, which is technically a string literal that gets ignored when not assigned.

What is the difference between a comment and a docstring? +

A # comment is stripped at compile time and exists only in the source. A docstring is a real string object stored on the module, function, or class and accessible at runtime via __doc__ and help().

How do I write a good comment? +

Explain intent and reasoning that the code cannot express by itself — why a workaround exists, why a constant has its value. Avoid comments that merely restate the code, since they drift out of date and add noise.

Are docstrings required? +

Not by the interpreter, but they are strongly recommended for public modules, classes, and functions. Tools like help(), IDEs, and documentation generators rely on them.