Question

Multiline Comments in Python: Docstrings and Commenting Blocks

pythoncommentsdocumentation

Question

How can I create multi-line comments in Python? Many programming languages provide block comment delimiters such as:

/*
  comment text
*/

What is the Python equivalent for commenting out multiple lines of text or code?

Short Answer

Python has no dedicated block-comment syntax like /* ... */. To comment multiple lines, place # at the start of each line. Triple-quoted strings can look like multiline comments, but they are actually string literals and are best used as docstrings for documentation.

Concept

Python comments begin with # and continue to the end of the current line:

# This is a comment

Unlike languages such as JavaScript, Java, C, and CSS, Python does not have a special block-comment delimiter such as /* ... */.

For a block of ordinary comments, use # on every line:

# Explain why this calculation exists.
# The API sends amounts in cents.
# Convert to dollars before displaying the value.
price_in_dollars = price_in_cents / 100

Python also supports triple-quoted strings using ''' or """. When a triple-quoted string is the first statement in a module, class, or function, Python treats it as a docstring: documentation that tools and code can access.

def calculate_total(prices):
    """Return the sum of all prices."""
    return sum(prices)

A standalone triple-quoted string elsewhere in code may appear to work as a comment, but Python still creates a string object while executing that location. Therefore, use # for comments and use docstrings for documentation.

Mental Model

Think of # as a marker that tells the Python reader: “ignore the rest of this line.” For several lines, put the marker on each line.

A docstring is different: it is like a label attached to a function, class, or file. It is meant to describe what that code does, and Python can keep that label available for help tools.

So:

  • # is a private note for readers of the code.
  • A docstring is documentation attached to a program object.
  • A standalone triple-quoted string is an unused piece of text, not a true comment block.
Take Quiz

Syntax and Examples

Use # for normal comments.

# This script greets a user.
# It asks for a name and prints a message.
name = input("Enter your name: ")
print(f"Hello, {name}!")

Most Python editors can add or remove # from selected lines with a keyboard shortcut. This is the usual way to temporarily comment out several lines of code.

Use a docstring to document a module, function, or class:

def is_even(number):
    """Return True when number is divisible by 2."""
    return number % 2 == 0

print(is_even(8))  # True

A multiline docstring can describe parameters, return values, or important behavior:

def convert_celsius_to_fahrenheit(celsius):
    """Convert a Celsius temperature to Fahrenheit.

    Args:
        celsius: Temperature in degrees Celsius.

    Returns:
        The equivalent temperature in degrees Fahrenheit.
    """
    return celsius * 9 / 5 + 32

Avoid using triple quotes merely to disable code:

# Not recommended as a comment technique:
"""
print("This is not intended to run")
"""

Although print() does not run here, the triple-quoted text is still a string literal. Use # instead.

Step by Step Execution

Consider this code:

# Store the number of completed tasks.
completed_tasks = 3

"""This is a standalone string literal.
It is not a regular Python comment.
"""

print(completed_tasks)

Step by step:

  1. Python reads the first line beginning with # and ignores it completely.
  2. Python assigns 3 to completed_tasks.
  3. Python evaluates the triple-quoted string literal. Because it is not assigned to a variable or used elsewhere, it has no useful result.
  4. Python runs print(completed_tasks).
  5. The program outputs:
3

Now compare it with a function docstring:

def greet(name):
    """Return a greeting for name."""
    return f"Hello, {name}!"

print(greet.__doc__)

The first string inside greet becomes the function's docstring. The output is:

Return a greeting for name.

Real World Use Cases

Comments and docstrings help developers understand code that is not obvious from its syntax.

  • Explaining business rules: Why a discount applies only after a particular date.
  • Clarifying external APIs: Why a request uses a specific header or data format.
  • Documenting public functions: What inputs a reusable function accepts and what it returns.
  • Marking temporary work: A short # TODO: note for an improvement that still needs to be made.
  • Explaining non-obvious performance choices: Why a value is cached or why a loop is structured unusually.
  • Temporarily disabling code while debugging: Prefix selected lines with #, then restore them after testing.

Example of an explanation that adds useful context:

# The payment provider expects the amount as the smallest currency unit.
amount_in_cents = int(amount_in_dollars * 100)
Take Quiz

Real Codebase Usage

In real Python projects, comments are usually brief and explain why, not the obvious what.

# Retry because the supplier API occasionally returns temporary 503 errors.
response = request_with_retry(url)

This is more useful than repeating the code:

# Make a request with retry.
response = request_with_retry(url)

Docstrings are commonly used for public modules, classes, and functions. They help IDEs, documentation generators, and Python's built-in help() function.

def find_user(user_id):
    """Return the user record for user_id, or None when it does not exist."""
    return users.get(user_id)

A common validation pattern combines a docstring, a guard clause, and a focused comment only when the reason is not obvious:

def send_email(address, message):
    """Send message to address and return whether delivery was accepted."""
    if not address:
        return False

    # Avoid calling the email provider when validation already failed.
    return email_client.send(address, message)

Do not leave large commented-out sections in committed code. Version control systems such as Git preserve history, so deleting obsolete code is usually cleaner.

Common Mistakes

Expecting /* ... */ to work

Python does not support C-style block comments.

/* This is invalid Python */

Use # instead:

# This is valid Python.

Treating triple-quoted strings as ordinary comments

This may look like a block comment:

"""
Temporary note
"""

But it is a string literal. It can be a valid docstring when placed first inside a module, class, or function. For ordinary notes, prefer #.

Putting a docstring in the wrong place

For Python to recognize a string as a function docstring, it must be the first statement in the function body.

def add(a, b):
    result = a + b
    """This is not the function docstring."""
    return result

Correct version:

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

Commenting what the code already says

Avoid comments that do not add information:

# Set count to zero.
count = 0

A better comment explains a reason or constraint:

# Start at zero because no records have been processed yet.
count = 0

Forgetting that # comments end at the line break

# This comment ends here
and_this_is_code = True

Add # to each comment line.

Comparisons

Feature# commentsDocstrings ("""...""")Standalone triple-quoted strings
Primary purposeNotes for code readersDocumentation for modules, classes, and functionsUsually an unused string; avoid using as comments
Can span multiple linesYes, with # on each lineYesYes
Retained by Python at runtimeNoUsually available through __doc__Evaluated as a string literal
Visible to help() and documentation toolsNoYesNo useful documentation role
Best useExplain why code existsDescribe an API or behaviorRarely needed by itself

# comments can also appear after code, but use inline comments sparingly:

max_attempts = 3  # Required by the external API rate-limit policy.

Use an inline comment only when it remains readable and provides useful context.

Take Quiz

Cheat Sheet

# One-line comment

# First line of a comment block
# Second line of a comment block
# Third line of a comment block
def function_name(value):
    """A docstring documents the function."""
    return value
  • Python has no /* ... */ comment syntax.
  • Use # for ordinary single-line and multi-line comments.
  • Add # to every line in a comment block.
  • Use """...""" or '''...''' as a docstring only when it is the first statement in a module, class, or function.
  • Do not rely on standalone triple-quoted strings for commenting out code.
  • Prefer comments that explain why over comments that restate what the code does.
  • Use your editor's “toggle line comment” command to comment or uncomment selected lines quickly.

FAQ

Does Python have multiline comments?

Python has no dedicated multiline or block-comment syntax. Use # at the beginning of every line you want to comment.

Can I use triple quotes for comments in Python?

Triple quotes create multiline strings. Use them for docstrings. A standalone triple-quoted string can look like a comment but is not the recommended way to write comments.

What is the Python equivalent of /* ... */?

There is no direct equivalent. Write a # on each line, usually with your editor's line-comment shortcut.

Can a comment appear after Python code on the same line?

Yes.

port = 8080  # Local development server port

Keep inline comments short so the line stays readable.

What is a docstring in Python?

A docstring is a string literal placed first in a module, class, or function. It documents that object and is available through __doc__ and help().

Should I comment out old code instead of deleting it?

Usually no. Delete unused code and rely on Git or another version-control system to recover it if necessary.

Which quote style should I use for docstrings?

Both """ and ''' work. Double triple quotes are the common convention, especially when the text may contain apostrophes.

Take Quiz

Mini Project

Description

Create a small order-total function with a useful docstring and focused line comments. This demonstrates the difference between documentation that describes a function's contract and comments that explain a business rule.

Goal

Write a function that calculates an order total, applies a discount when eligible, and documents its behavior clearly.

Requirements

Use a function named calculate_order_total.

Accept a list of prices and a boolean indicating whether the customer is a member.

Return the total price after applying a 10% member discount.

Add a multiline docstring as the first statement in the function.

Use # comments only where they explain a non-obvious rule.

Print the result for at least one example order.

Take Quiz

Keep learning

Related questions

View more