Coding

Comments in Python: Single-Line and Multiline Examples

Comments in Python start with a hash character (#) and run to the end of the line, and Python ignores everything after the #. There is no separate multiline comment syntax: to comment several lines, put a # at the start of each one.

# This is a comment on its own line
price = 20  # This is an inline comment
# A second line
# of the same note

The rest of this article covers each kind of comment, the cases where a # is not a comment, how docstrings differ, and the style rules from PEP 8.

Single-line comments

The language reference defines a comment this way: it starts with a hash character that is not part of a string literal, and ends at the end of the physical line. A comment can sit on a line by itself, or after code on the same line.

# Convert the price to cents
cents = int(price * 100)

The comment explains why or what is happening for the next reader. Python does not run it, store it, or make it available while the program runs.

Inline comments

An inline comment shares a line with a statement:

retries = 3  # the server drops about one request in ten under load

PEP 8 says inline comments should be used sparingly, separated from the statement by at least two spaces, and start with # and a single space. It also warns that an inline comment is distracting when it states the obvious, as in x = x + 1 # increment x. Keep inline comments for information the code cannot show on its own, such as a reason for a magic number.

Multiline comments

Python has no block comment delimiter like /* ... */ in C or JavaScript. The standard way to write a comment across several lines is one # per line:

# Retry the upload up to three times.
#
# The storage service sometimes returns a temporary error right
# after a bucket is created, so a short retry loop is enough.
for attempt in range(3):
    ...

PEP 8 calls this a block comment. Each line starts with # and a single space, and paragraphs inside the block are separated by a line containing only a single #. Block comments are normally indented to the same level as the code they describe.

A backslash does not help here. The language reference states that a line ending in a backslash cannot carry a comment, and that a backslash does not continue a comment. If your comment is long, start a new line with #.

Are triple-quoted strings comments?

You will often see this used as a multiline comment:

"""
This text spans
several lines.
"""
value = 10

It runs without an error, but it is not a comment. It is a string literal sitting in the code. PEP 257 explains that a string literal that is the first statement of a module, function, class or method is a docstring and becomes the object's __doc__ attribute. String literals elsewhere are not recognized by the bytecode compiler as docstrings and are not accessible as runtime object attributes. In other words, the text is not documentation, but it is also not a real comment.

The practical advice: use # lines for comments, and keep triple-quoted strings for docstrings and for real multi-line text values. A # comment also makes your intent clear to anyone reading the file, because nobody has to wonder whether the string is used somewhere.

When a # is not a comment

The Python tutorial points out that a comment may appear at the start of a line or after whitespace or code, but not within a string literal. A hash character inside a string is just a hash character:

# this is the first comment
spam = 1  # and this is the second comment
text = "# This is not a comment because it's inside quotes."
print(text)

Example output:

# This is not a comment because it's inside quotes.

The first two # characters start comments. The third is part of the text, so print shows it. This matters when you build strings such as hex colors ("#ff8800") or URL fragments, where the # must stay.

Comments versus docstrings

A docstring documents what a module, function, class or method does. It is a triple-quoted string that comes first in the body, and PEP 257 recommends triple double quotes (""") for consistency.

def area(width, height):
    """Return the area of a rectangle in square units."""
    # Negative sizes would silently give a positive area when both are negative
    if width < 0 or height < 0:
        raise ValueError("width and height must be 0 or greater")
    return width * height

print(area.__doc__)
help(area)

Here the docstring answers "what does this function do?", and the # comment explains "why is this check here?". Python keeps the docstring, so area.__doc__ returns it and help(area) displays it. The comment is gone as soon as the file is parsed.

PEP 8 asks for docstrings on all public modules, functions, classes and methods. For non-public methods it says a docstring is not necessary, but you should have a comment that describes what the method does, placed after the def line.

CommentDocstring
Syntax# to end of lineString literal, first statement of a module, function, class or method
Available at runtimeNoYes, as __doc__
Read by help()NoYes
Typical contentWhy the code does somethingWhat the code does and how to call it

Comment style rules from PEP 8

  • "Comments that contradict the code are worse than no comments." Update comments whenever the code changes.
  • Write comments as complete sentences, and capitalize the first word unless it is an identifier that starts with a lowercase letter.
  • Start block comments with # and a single space.
  • Limit the line length of comments and docstrings to 72 characters. The limit for code is 79.
  • Do not restate the code. A comment such as # loop over users above for user in users: adds nothing.

A useful test: if deleting the comment would leave a reader confused about why the code is written that way, keep it. If the code already says the same thing, delete it.

Commenting out code

Putting # in front of a line disables it without deleting it, which is handy while debugging:

print("start")
# print("this line is skipped")
print("end")

Example output:

start
end

Most code editors can add or remove # on every selected line with one shortcut, but the shortcut differs by editor, so check yours. Do not leave large amounts of disabled code in a file for long. Version control already remembers old code, and stale commented-out lines make the file harder to read.

A special comment: the encoding declaration

One kind of comment has an effect. If a comment in the first or second line of a script matches the pattern coding[=:]\s*([-\w.]+), Python treats it as an encoding declaration:

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

The language reference says that without a declaration the default source encoding is UTF-8, so for ordinary modern files you do not need this line. If the declaration is on the second line, the first line must also be a comment-only line.

Common mistakes

  • Forgetting the space or the #. Text without a leading # is code, and Python raises a SyntaxError. Compare with the examples in Python print function examples, where a stray character in a line is the usual cause.
  • Expecting # to comment out the rest of a multi-line statement. A comment ends only the physical line. Lines you want disabled each need their own #.
  • Putting # inside quotes and expecting a comment. Inside a string it is plain text.

If you are writing your first script, Hello World in Python shows how to create and run a file where you can try these comments.

Frequently asked questions

Does Python have multiline comments?
Not as a separate syntax. Python only has the # comment, which ends at the end of the physical line. To write a multiline comment, start every line with #. A triple-quoted string placed on its own line is sometimes used instead, but it is a string expression, not a comment.
What is the difference between a comment and a docstring?
A comment starts with # and is ignored by Python. A docstring is a string literal that is the first statement of a module, function, class or method, and Python stores it in the object's __doc__ attribute so that help() and documentation tools can read it.
How many spaces go before an inline comment?
PEP 8 says inline comments should be separated from the statement by at least two spaces, and should start with # followed by a single space.
Can a comment continue after a backslash at the end of a line?
No. The Python language reference says a line ending in a backslash cannot carry a comment, and a backslash does not continue a comment. Each comment line needs its own #.

Sources