What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Python does not have a dedicated block-comment delimiter such as /* … */. A Python comment begins with # outside a string literal and ends at the end of that physical line. To write a multiline comment, place # at the start of each line.

Triple quotes create string literals. They are appropriate for docstrings in the right position, but they are not Python block-comment syntax.

How to write a multiline comment in Python

Use one hash character for every line:

# Explain why the cache is cleared here.
# The next request must read the latest configuration.
# Do this before starting the worker threads.

This is the portable, idiomatic form of a Python block comment. Each comment line should normally use the same indentation as the code it describes:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

def refresh_cache(client):
    # The service can return stale data immediately after an update.
    # Clear the local cache before requesting the replacement value.
    client.cache.clear()
    return client.fetch_config()

PEP 8 recommends writing block comments as complete sentences, keeping them synchronized with the code, and putting them at the same indentation level as the code that follows. For separate paragraphs, use a comment-only line containing a hash:

# Validate the input before opening the file. This avoids creating an
# empty output file when the supplied path is invalid.
#
# The validation also makes the error message independent of the OS.
validate_path(path)

Inline comments versus block comments

A comment after executable code is an inline comment. Leave at least two spaces between the statement and #, then add one space after the hash:

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

timeout = 30 # Seconds before the request is cancelled.

Use an inline comment for a short explanation of one value or expression. Use a block comment when the explanation applies to several lines or describes a decision made by the following code.

Comment type Example Best use
Line comment # Fetch the current user. One short note
Block comment # Check the token first. / # The API rejects expired tokens. Several related lines of explanation
Inline comment retries = 3 # Keep startup quick. A value-specific clarification

Commenting several lines of existing code

To temporarily disable a block of Python code, add # to every line:

# connection = open_connection(config)
# response = connection.send(request)
# print(response.status_code)

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

This is preferable to surrounding the code with triple quotes. Editors can add or remove line comments, and command-line tools such as grep recognize the lines as comments. It also avoids turning the disabled code into a string literal.

A comment does not continue because a line ends with a backslash. The next physical line needs its own #.

# This explanation does not continue to the next line
# unless the next line has its own hash.

The backslash has no block-comment meaning. Put # on each physical line instead.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Comments inside lists, dictionaries, and function calls

Python permits comments on implicitly continued lines inside parentheses, brackets, and braces:

supported_formats = [
    “json”, # Used by the public API.
    “csv”, # Used by the reporting command.
    “yaml”, # Used by deployment configuration.
]

The same rule works in a function call or dictionary:

request = send_request(
    url,
    timeout=10, # Prevent a stalled server from blocking the job.
    verify_tls=True, # Required for production endpoints.
)

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Do not place a comment inside a string literal. In the following example, the hash is ordinary string content:

message = “””
# This is displayed as part of the message.
“””

Why triple-quoted strings are not block comments

This code is valid Python, but it creates an unused string literal:

“””
This looks like a multiline comment.
“””

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Python still lexically parses the content as a string. Newlines are retained in the string value, escape sequences may be processed, and an unescaped matching triple-quote sequence ends the string. A malformed or prematurely terminated string can therefore cause a syntax error.

Triple quotes also have runtime and tooling consequences. A string placed as the first statement in a module, class, function, or method becomes that object’s docstring. A standalone string elsewhere is not automatically a docstring, and it is not the same as a comment.

Docstrings: the correct use of triple quotes

Use a docstring to document a public module, class, function, or method. It must be the first statement in that definition:

def load_config(path):
    “””Load application settings from path.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

    The file must contain valid UTF-8 JSON.
    “””
    with open(path, encoding=”utf-8″) as file:
        return json.load(file)

Python exposes the text through load_config.__doc__, and documentation tools can use it. A triple-quoted string in the middle of a function does not become the function’s docstring:

def load_config(path):
    log.debug(“Starting configuration load”)
    “””This is not the function docstring.”””
    return read(path)

For a multiline docstring, use a one-line summary, a blank line, and then the details. Put the closing triple quotes on their own line. PEP 257 recommends triple double quotes; use a raw prefix such as r”””…””” when the docstring contains backslashes that should not be interpreted.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Using PyCharm to add comments and docstrings

PyCharm can insert a documentation-string stub rather than making you type its structure manually:

  1. Place the caret inside the function, method, or class.
  2. Press Alt+Enter.
  3. Choose Insert documentation string stub.

To select the generated docstring style, open Settings with Ctrl+Alt+S, then go to Python | Tools | Integrated Tools. Select a format from the Docstring format dropdown.

PyCharm may also generate a stub when you type the opening triple quotes and press Enter or Space. The Space behavior requires Insert pair quote to be cleared under the editor’s Smart Keys settings.

Adding or removing comment markers in VS Code

VS Code provides editor commands for line and block comment operations. Select the lines you want to change, then open File > Preferences > Keyboard Shortcuts. On Windows and Linux, Ctrl+K Ctrl+S opens the keyboard-shortcut editor. You can also run Preferences: Open Keyboard Shortcuts from the Command Palette.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Search for editor.action.addCommentLine to find the command that adds line-comment markers. VS Code also exposes editor.action.blockComment. Exact shortcuts can vary with the operating system, keyboard layout, extensions, and your custom settings, so check the shortcut shown in your installation instead of relying on a platform-specific assumption.

You can assign a shortcut in keybindings.json. For example: { “key”: “ctrl+alt+c”, “command”: “editor.action.addCommentLine” }.

For Python, line comments are usually the better choice even if an editor offers a generic block-comment command, because Python itself has no block-comment delimiter.

Blank lines, indentation, and the interactive interpreter

A logical line containing only whitespace and/or a comment is ignored by Python. A comment-only line can therefore separate sections without affecting execution:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

import json

# Load and validate the input.
data = load_data()
validate(data)

# Transform only after validation succeeds.
result = transform(data)

There is one interactive-interpreter detail to remember: in the standard Python prompt, an entirely blank line terminates a multiline statement. A line containing only a comment is not the same as an empty line. This can matter when entering a function or loop interactively.

Encoding declarations are a special kind of comment

A comment on the first or second source line can declare the file encoding when it matches Python’s encoding-declaration pattern:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

# -*- coding: latin-1 -*-

If the declaration is on line two, line one must also be comment-only. Modern Python source defaults to UTF-8, so most new files do not need an encoding declaration.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Practical comment guidelines

  1. Explain reasons, not obvious syntax. # Add 1 to count rarely helps. Explain why the count needs adjustment.
  2. Keep comments near the code they describe. A distant explanation becomes unreliable after refactoring.
  3. Use comments for decisions and constraints. Mention an API limitation, compatibility requirement, security condition, or non-obvious algorithm choice.
  4. Update comments with code. A comment that describes an old behavior is worse than no comment because it sends maintenance work in the wrong direction.
  5. Use docstrings for discoverable API documentation. If users should see the explanation through help(), IDE features, or generated documentation, it likely belongs in a docstring.
  6. Do not use comments to hide unfinished code indefinitely. For temporary work, a short tracking reference such as # TODO(PROJ-142): remove compatibility branch is more useful.

Quick comparison

Syntax What Python creates Use it for
# text A comment ignored by the syntax parser Notes, explanations, and disabled lines
“””text””” A triple-quoted string literal Docstrings when placed first in a definition; ordinary strings when assigned or used
r”””text””” A raw triple-quoted string literal Docstrings or strings containing backslashes that should remain literal

FAQ

Does Python support /* … */ block comments?

No. Python comments use # and end at the physical line ending. Write a multiline comment with one # on every line.

Can I use triple quotes as a multiline comment?

Not technically. Triple quotes create a string literal. An unused string may appear to act like a comment, but it can be parsed as a string, confuse tools, and become a docstring if placed first in a definition.

What is the difference between a docstring and a comment?

A comment starts with # and is ignored. A docstring is a string literal that is the first statement in a module, class, function, or method; Python exposes it through the object’s __doc__ attribute.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

How do I comment out multiple lines in Python?

Add # to each line, preferably using your editor’s line-comment command. Do not wrap executable code in triple quotes.

Can a Python comment continue onto the next line with a backslash?

No. A backslash does not extend a comment. The next physical line needs its own #.

Can comments appear inside a Python list or function call?

Yes. Comments are allowed on implicitly continued lines inside parentheses, brackets, and braces, such as a list with a comment beside each item.

The Bottom Line

For a Python block comment, use # on every line and indent those lines with the code they explain. Use inline comments for short, value-specific notes. Reserve triple-quoted strings for actual string data and docstrings, where their position and contents have defined meaning.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

References: Python lexical analysis, PEP 8 comments, and PEP 257 docstrings.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.