Sitelet https://www.askpython.com/python/python-comments

Python Comments: Write Multiline Notes

During debugging, you might set aside a few statements while testing the rest of a Python program. A comment starts with #, and Python ignores the text that follows on that line.

This article shows how to comment out a complete block and explains how comments differ from docstrings and directives that Flake8 and Black read.

TL;DR: Python Comments

Python uses # for source comments, while docstrings carry documentation for functions and classes. Choose a source comment for local context because it stays beside the implementation.

  • Use an editor’s line-comment toggle as a shortcut, not a different Python syntax.
  • PEP 8 and PEP 257 cover comment and docstring conventions.

What Is a Python Comment?

A Python comment is source text that begins with a hash character outside a string and continues to the end of that physical line. Python’s lexical analyzer ignores it when it reads the program, so a comment does not produce a value or run as a statement. See the language reference on comments for the lexical rule.

The distinction depends on context. In status = "#ready", the hash is part of the value because it appears inside quotes. In status = "ready" # used after validation, the hash starts a comment after the assignment and text after it belongs to that comment.

For a multiline note, put # on each physical line, as Python has no dedicated block-comment syntax.

Source formWhat it means
# A full-line comment explains the decision below.Python ignores the rest of this physical line.
attempt_limit = 3 # Retry after a temporary failure.The assignment runs, then the comment begins.
message_key = "#retry"The hash is a character in the string value.

Indent a comment line at the level of the statement or block it describes. A blank line inside a longer comment can contain only #, keeping the whole paragraph within the comment block.

How to Write and Comment Out Python Code Step by Step

The example below records a decision beside an assignment and keeps a test statement inactive. It also shows the editor-ready form for a longer note.

Step 1: Add a Comment to Each Line

The first full-line note describes a local rule. The inline note follows its assignment after two spaces, as PEP 8 recommends for inline comments.

This file combines a full-line comment, a multiline comment, an inline comment, a hash inside a string, a disabled statement and a function docstring. Save it as comments_demo.py so the example can be run as shown.

# A full-line comment explains the decision below.
# A multiline comment uses one # comment per physical line.
attempt_limit = 3  # Retry after a temporary failure.

message_key = "#retry"  # The hash inside this string is data.

# print("This line stays disabled while its # remains here.")
def retry_message():
    """Return the label shown after a temporary failure."""
    return message_key

print(attempt_limit)
print(message_key)
print(retry_message.__doc__)

Run the file with this command:

python3 comments_demo.py

I ran the command and captured its output:

3
#retry
Return the label shown after a temporary failure.
Terminal output showing a Python comment example and function docstring
Running comments_demo.py prints the assigned values and the function’s docstring.

The output shows the integer assignment, keeps #retry as string data, and reads the function description through __doc__.

Step 2: Comment Out a Complete Block

Select a complete statement block and use your editor’s line-comment toggle. It adds a marker to each selected line. Review the changed source before running it.

Key bindings vary by editor and keymap. Ctrl+/ is common on Windows or Linux, while some macOS setups use Command+/. Check the editor menu if those keys do something else.

The function temporarily contains pass while its operation is disabled. Save this program as comment_block_demo.py.

# Keep a function block valid while its operation is disabled.
def process_pending_record():
    # The processing call is disabled for this test.
    pass

process_pending_record()
print("Function block remains valid.")

Run the file with this command:

python3 comment_block_demo.py

I ran the command and captured this output:

Function block remains valid.
Terminal output showing pass preserving a valid Python function block
Running comment_block_demo.py confirms that the function remains valid with pass.

A partial expression left by a comment can leave a dangling operator, so disable complete statements and run a syntax check.

A block that loses its only statement needs a placeholder such as pass until the original code returns. The language reference on compound statements explains why a function or conditional suite must contain a statement.

When Are Triple Quotes Comments, Strings, or Docstrings?

Triple-quoted text becomes a docstring in the first-statement position of a module, function, class or method. Elsewhere, store multiline text the program needs in a string variable.

Where triple quotes appearPython’s interpretationSuitable purpose
First statement in a functionFunction docstring, available as __doc__Document the function for callers
Later statement in a functionString expression with no function-documentation roleCreate a string value the program uses
Inside a larger expressionString content that can join adjacent stringsBuild multiline text values

Use Docstrings for Documentation

PEP 257 recommends a concise summary line for a multiline docstring, followed by a blank line and a longer explanation when one is needed. Explain behavior, important inputs and return values, or exceptions a caller must handle. The PEP 257 conventions describe the format, and the AskPython guide to Python docstrings gives examples.

Why Triple Quotes Can Change Code

Python parses a quoted expression even when its value is unused, so malformed quoting can stop a file from running. Adjacent string literals combine, and a quoted block between two parts becomes part of that value.

When Comments Carry Type Information

PEP 484 defines type comments for variable assignments and function signatures. Static type checkers can read them as type information.

Use type comments when a project’s compatibility prevents annotations. For new code that supports annotations, prefer annotation syntax because it places the type alongside the function or variable declaration. See PEP 484’s type-comment section for the supported forms.

Use a type-ignore comment only after checking the reported warning, since suppressing a valid diagnostic can hide a mismatch with the function’s intended interface.

Type hints describe expected values for a checker. They do not validate data while the program runs, so code that reads files, network responses or user input still needs runtime checks.

When Tools Read Comment Directives

Some tools assign extra meaning to specific comment text. Flake8 recognizes # noqa to suppress a lint warning, while Black uses # fmt: off and # fmt: on to skip formatting within a block.

Keep these exceptions narrow. Flake8 can name an individual rule after noqa, and Black requires its start and end markers to stay in the same block and indentation level. See the Flake8 guide to ignored violations and Black’s formatting directives for their scope rules.

Shebang and Encoding Comments

Some top-of-file comments carry interpreter or encoding metadata.

A coding declaration may appear in the first or second source line, and Python uses it to decode the file. Python 3 uses UTF-8 by default, so leave it out unless the file uses a different encoding.

If it appears on line two, the first line must also be comment-only. See the encoding declaration rule.

A first line such as #!/usr/bin/env python3 is a shebang: Unix-like systems can use it to select the interpreter when the script runs directly. Invoking the file with python3 selects the interpreter at the command line instead. The Python documentation on using scripts on Unix and PEP 394 explain the convention.

Write Comments That Explain Intent

A useful comment records a reason or constraint that the expression cannot show on its own. For example, a retry limit can state why attempts stop there instead of narrating that a counter increments.

Review comments when the code changes. An obsolete explanation points readers toward behavior the program no longer has. Give a function or variable a clearer name when the note only translates its name into a sentence.

PEP 8 recommends complete sentences and sparse inline comments. Leave one space after the marker in a block comment and two spaces before an inline marker. Keep comment lines to 72 characters, splitting longer explanations into separate lines.

For temporary debugging, comment out the smallest useful section and restore or remove it when the test is complete. Version control keeps earlier code available without leaving inactive statements among the code that runs.

TODO and FIXME are ordinary comment text, not Python keywords. Use them to label unfinished work with a specific action, such as handling an empty response. Resolve or update the note before a change ships.

Common Python Comment Errors

A comment can affect nearby syntax, while disabling only part of an expression can leave invalid code. I keep a hash inside quotes when it is data, and comment out complete statements rather than fragments.

  • Hash inside a string: the value contains # as text. Keep it inside the quotes.
  • Commented expression fragment: a dangling operator can cause SyntaxError. Disable the whole statement.
  • Empty function or conditional suite: Python reports IndentationError. Use pass temporarily.
  • Triple-quoted text in code: a string expression may join adjacent strings. Use # comments for notes and docstrings for API documentation.

For a parsing check after editing, run python3 -m py_compile comments_demo.py. It checks syntax without running the program’s top-level statements.

The table also helps distinguish an empty suite from an inactive statement: pass keeps the suite valid, while a fragment can leave Python with incomplete syntax.

Conclusion: Match Each Text to Its Job

For syntax details, read the Python language reference for comments and PEP 8’s block-comment guidance. The PEP 257 conventions cover docstrings, and the AskPython article on Python functions explains definitions and calls.

FAQ

These answers cover a multiline note, an editor shortcut, and conventions that some tools read.

Does Python support /* */ comments?

No. Write a separate line comment for each line in a multiline note.

What shortcut comments out several Python lines?

The shortcut depends on the editor and its keymap. Some editors use Ctrl+/ on Windows or Linux and Command+/ on macOS to toggle comments on selected lines.

What does a type-ignore comment do?

A type checker can treat a type-ignore comment as an instruction to suppress a diagnostic for that line. Python itself treats the text as a comment.

Are TODO and FIXME Python keywords?

No. They are ordinary comment text. Python gives them no special behavior, although an editor or task scanner can search for those labels.

Pankaj Kumar
Pankaj Kumar

I have been working on Python programming for more than 12 years. At AskPython, I share my learning on Python with other fellow developers.

Articles: 261