☰

Comments in Python Language

Comments in Python: Single Line, Multi Line and Docstrings

Open a program you wrote three months ago. Even if the code is correct, you may stare at a line and wonder why you wrote it that way. Now imagine a stranger reading it, or a new teammate on Monday morning. Code tells the computer what to do. Comments tell people why.

A comment is a note inside your code that Python ignores when the program runs. It does not change the result, but it changes how fast another person, or you in the future, can understand and fix the program. Good comments explain the reasons behind the code, flag the tricky parts, and mark work that is not finished. They are also a handy tool for switching a line off while you test.

In this tutorial, we explain how to write a comment in Python, and then go through single line comments, inline comments and the so called multi line comment. We show what Python really does with triple quotes, how docstrings differ from comments, and how to comment out code quickly. We finish with the style rules from PEP 8, examples of good and bad comments, and the common mistakes. Every example was run on Python 3.13.

What is a Comment in Python?

A comment is text that the Python interpreter skips. You write it for human readers. Comments are used to explain what a block of code does, to describe why a choice was made, to leave a reminder, and to stop a line from running while you test.

How to Comment in Python?

A comment starts with a hash sign. Everything from the hash to the end of that line is ignored. The comment can sit on its own line, or after some code.

python
# This is a comment. Python ignores it.
print("Hello")  # an inline comment, after code
output
Hello

Only the print line ran. The comments left no trace and printed nothing.

Types of Python Comments

People usually group comments into single line and multi line comments. The two groups are useful for learning, but the second one needs care, which is explained below.

Single Line Comment in Python

A single line comment uses one hash sign and fits on one line.

python
# Comment

Here is a single line comment in a working program:

python
# This is a comment.
print("Hello")
output
Hello

Inline Comments

An inline comment sits on the same line as the code, after it. Leave at least two spaces between the code and the hash, and one space after the hash. This is the PEP 8 rule, and it keeps the line readable.

python
price = 100
price = price * 1.18  # add 18 percent GST

A Hash Inside Text Is Not a Comment

If the hash sits inside quotes, Python treats it as part of the text.

python
print("Item # 5")
print('Price: Rs 100 # not a comment')
output
Item # 5
Price: Rs 100 # not a comment

Multi Line Comment in Python

Python has no special syntax for a multi line comment. There are two ways people write one, and they are not the same thing.

Way 1: several lines that each start with a hash. This is the real way, and the one that Python’s own style guide recommends. Most editors can add the hash to a whole block with one shortcut.

python
# Step 1: read the marks
# Step 2: find the average
# Step 3: print the result
marks = [70, 80, 90]
print(sum(marks) / len(marks))
output
80.0

Way 2: a triple quoted string. Three single quotes or three double quotes can wrap text over many lines. Python does not treat this as a comment. It reads it as a string. Since nothing uses that string, Python throws it away, so it behaves like a comment.

python
"""
This is a multi line text.
Python reads it as a string,
and then throws it away because nothing uses it.
"""
print("Triple quotes ran without error")
output
Triple quotes ran without error

Two mistakes break this. The first is curly quotes, which text copied from a web page or a word processor often contains. The second is opening with one kind of quote and closing with another. The marks must be straight, three of them, and the same at the start and the end. Here is what Python says to each broken version:

python
bad_examples = [
    "\u2018\u2018comment\u2019\u2019",
    "\u201c\u201c\u201cText\u201d\u201d\u201d",
    "'''comment\"\"\"",
]
for text in bad_examples:
    try:
        compile(text, "<page>", "exec")
    except SyntaxError as e:
        print("SyntaxError:", e.msg)
output
SyntaxError: invalid character '‘' (U+2018)
SyntaxError: invalid character '“' (U+201C)
SyntaxError: unterminated triple-quoted string literal (detected at line 1)

Comment or String: What Python Really Does

You can see the difference with the ast module, which shows how Python reads your code. A hash comment leaves nothing behind. A triple quoted line becomes a real statement in the code tree.

python
import ast

with_hash = "# just a comment\nx = 1"
with_triple = '"""just a string"""\nx = 1'
print([type(node).__name__ for node in ast.parse(with_hash).body])
print([type(node).__name__ for node in ast.parse(with_triple).body])
output
['Assign']
['Expr', 'Assign']

The first list has only the assignment, so the comment is gone. The second list has an extra Expr, which is the string. It is harmless and does nothing, but it is still code. And if you store the string in a variable, it is a normal value and not a comment at all:

python
note = """This text is stored in a variable."""
print(note)
output
This text is stored in a variable.

For this reason, the better habit is to use hash lines for comments, and keep triple quotes for docstrings.

Docstrings: Comments That Python Keeps

A docstring is a triple quoted string placed as the very first line inside a function, class or module. Python stores it, so tools and the help function can show it. It is the one case where triple quotes are the right choice.

python
def area(length, width):
    """Return the area of a rectangle."""
    return length * width

print(area.__doc__)
print(area(4, 5))
output
Return the area of a rectangle.
20

The attribute __doc__ holds the docstring. Classes can have one too:

python
class Student:
    """A student with a name and marks."""

    def __init__(self, name, marks):
        self.name = name
        self.marks = marks

print(Student.__doc__)
output
A student with a name and marks.

Longer functions can use several lines. Python keeps the line breaks, and removes the extra indent that comes from the code block (Python 3.13):

python
def average(values):
    """Return the average of a list of numbers.

    values: a list of numbers
    Returns a float.
    """
    return sum(values) / len(values)

print(average.__doc__)
output
Return the average of a list of numbers.

values: a list of numbers
Returns a float.

A normal comment never becomes a docstring. In the next example, the function has a comment but no docstring, so __doc__ is None:

python
def no_docstring():
    # this is only a comment
    return 1

print(no_docstring.__doc__)
output
None
Comment compared with docstring
Feature Comment with a hash Docstring
Written for People reading the code People using the function, and tools
Kept by Python No Yes, in __doc__
Where it goes Anywhere First line of a function, class or module
Marks One hash per line Three quotes at each end

Comment Out Code While Testing

A very practical use of comments is to switch off a line without deleting it. Put a hash in front of the line, and Python skips it.

python
# print("This line will not run")
print("Only this line runs")
output
Only this line runs

Most code editors have a shortcut that adds or removes the hash on every selected line. In VS Code and many other editors, it is Ctrl and the slash key on Windows and Linux, and Command and the slash key on a Mac. In PyCharm it is the same. IDLE uses Alt and 3 to comment a block, and Alt and 4 to remove it.

Comment Style: What PEP 8 Says

PEP 8 is the official Python style guide. Its advice on comments is short and worth following.

  • Start with a hash and one space. Write # Like this, and not #Like this.
  • Two spaces before an inline comment. Put at least two spaces between the code and the hash.
  • Keep block comments level with the code. A comment above a line should have the same indent as that line.
  • Keep lines short. PEP 8 suggests at most 72 characters for comments and docstrings.
  • Write full sentences, with the first word capitalised, unless it is a name.
  • Keep them up to date. A comment that is no longer true is worse than no comment.

Good Comments and Bad Comments

A comment should say something the code cannot say by itself. The best ones explain why.

Here is a bad comment. It repeats the code, so it adds nothing:

python
x = 10
x = x + 1  # add 1 to x

Here is a good one. It tells the reader a fact they could not see from the numbers:

python
price = 100
price = price * 1.18  # add 18 percent GST
What to write and what to avoid
Write a comment to Avoid a comment that
Explain why a choice was made Repeats what the code already says
Warn about a tricky or surprising part Is out of date and no longer true
Give the source of a formula or a rule Excuses messy code, which you should clean up instead
Mark work for later Hides old code that should be deleted

TODO Comments

A common habit is to mark unfinished work with the word TODO, so you can search for it later. Many editors highlight these.

python
# TODO: handle an empty list of marks

The Encoding Comment

You may see a line like the next one at the top of old files. It tells the interpreter the file encoding. In Python 3, files are read as UTF 8 by default, so you rarely need it. The line below is a special comment, but it is still a comment.

python
# -*- coding: utf-8 -*-

Common Mistakes With Python Comments

  • Curly quotes around a block. Quotes copied from a web page or a word processor cause a SyntaxError. Use straight quotes.
  • Mismatched triple quotes. Open and close with the same type, either three single or three double.
  • A hash inside text. It is part of the text and not a comment.
  • Using triple quotes in the middle of code and expecting a comment. It works, but it is a string, and it can show up as a docstring or add clutter. Use hash lines.
  • Commenting every line. Too many comments make code harder to read.
  • Leaving old comments. After you change the code, change the comment.
  • Forgetting the space after the hash. It still works, but it breaks the style rule.

Quick Reference

Comments quick reference
You want to Write
A single line comment # comment
A comment after code code # comment
A multi line comment One hash at the start of every line
A docstring Triple quotes as the first line of a function, class or module
Stop a line from running Put a hash in front of it
Read a docstring name.__doc__ or help(name)

Complete Script to Run Yourself

Here is the full script used to produce every output on this page. Copy it into a file, run it with Python 3, and compare the results.

python
# 1. hash comment
# This is a comment. Python ignores it.
print("Hello")  # an inline comment, after code

# 2. single line
# This is a comment.
print("Hello")

# 3. inline comment
price = 100
price = price * 1.18  # add 18 percent GST

# 4. hash in text
print("Item # 5")
print('Price: Rs 100 # not a comment')

# 5. block of hash lines
# Step 1: read the marks
# Step 2: find the average
# Step 3: print the result
marks = [70, 80, 90]
print(sum(marks) / len(marks))

# 6. triple quoted string
"""
This is a multi line text.
Python reads it as a string,
and then throws it away because nothing uses it.
"""
print("Triple quotes ran without error")

# 7. broken quotes
bad_examples = [
    "\u2018\u2018comment\u2019\u2019",
    "\u201c\u201c\u201cText\u201d\u201d\u201d",
    "'''comment\"\"\"",
]
for text in bad_examples:
    try:
        compile(text, "<page>", "exec")
    except SyntaxError as e:
        print("SyntaxError:", e.msg)

# 8. ast check
import ast

with_hash = "# just a comment\nx = 1"
with_triple = '"""just a string"""\nx = 1'
print([type(node).__name__ for node in ast.parse(with_hash).body])
print([type(node).__name__ for node in ast.parse(with_triple).body])

# 9. string in variable
note = """This text is stored in a variable."""
print(note)

# 10. docstring
def area(length, width):
    """Return the area of a rectangle."""
    return length * width

print(area.__doc__)
print(area(4, 5))

# 11. class docstring
class Student:
    """A student with a name and marks."""

    def __init__(self, name, marks):
        self.name = name
        self.marks = marks

print(Student.__doc__)

# 12. multi line docstring
def average(values):
    """Return the average of a list of numbers.

    values: a list of numbers
    Returns a float.
    """
    return sum(values) / len(values)

print(average.__doc__)

# 13. comment is not docstring
def no_docstring():
    # this is only a comment
    return 1

print(no_docstring.__doc__)

# 14. comment out
# print("This line will not run")
print("Only this line runs")

# 15. bad comment
x = 10
x = x + 1  # add 1 to x

# 16. good comment
price = 100
price = price * 1.18  # add 18 percent GST

A good comment saves the next reader a minute of guessing, and that reader is often you. Use a hash for notes, triple quotes for docstrings, and keep the notes short and true. Run the script above, move the hash around, and see what changes. Then read a few well written open source Python files, and watch how their authors explain the hard parts.

Popular Tags:

Comments in Python Comments in Python Language online course on python online course to learn python online python course online python course for beginners online python training course online training courses for python online training on python