How to Use Comments in Python
Learn how to write Python comments with #, use inline and multi-line explanations, and understand the difference between comments, string literals, and docstrings.
A comment is text in source code that helps people understand a program. Python normally ignores comments during execution, so comments are for the author and other developers rather than for the program's normal output.
Good comments explain the purpose of a statement, block, function, or program. They are most useful when they describe intent, assumptions, constraints, or an unusual decision that is not obvious from the code itself.
If you are new to running Python programs, review writing your first Python program and running Python code first.
Why comments are useful
Source code is written for both computers and humans. Python needs precise instructions, but people also need context. A comment can answer questions such as:
- What is this section of code intended to do?
- Why was this approach chosen?
- What assumption does this calculation make?
- Why is an unusual value, workaround, or order of operations necessary?
Avoid comments that merely repeat obvious code. For example, the comment in name = "Ava" # assign Ava to name adds little information. A comment such as timeout = 5 # keep the request from waiting indefinitely explains a decision that may not be obvious.
The hash character starts a Python comment
Python's standard comment marker is the hash character, written as #. A line comment begins at # and continues through the end of the current physical line. Python does not treat that text as executable Python code.
Full-line comments
A full-line comment appears on its own line, commonly above the code it describes:
# Display a greeting to the user
print("Hello, world!")
The comment documents the purpose of the statement. The print() call still runs.
Inline comments
An inline comment appears after executable code on the same line:
name = "Ava" # The name will be used in the greeting
print(name)
The assignment before # executes. Only the comment text after # is ignored. This also works with a function call:
print("Ready") # Tell the user the program can continue
Place a space before an inline comment so the code and explanation are easy to distinguish. Keep inline comments short; use a separate line when a longer explanation is needed.
Running code that contains comments
Consider this complete script:
# A small greeting program
name = "Ava" # Store the name for the message
print("Hello, " + name)
The terminal displays:
Hello, Ava
The two comments are part of the source code, but neither appears in the output. The interpreter executes the assignment and the print() call, while the comment text is an annotation for human readers.
Writing a multi-line explanation with #
Several consecutive lines beginning with # are the conventional way to write a multi-line comment or explanation:
# This program asks for a name.
# It then builds a greeting from the answer.
# The result is displayed on the final line.
name = "Ava"
print("Hello, " + name)
Each physical line has its own #. This form is appropriate for ordinary notes, section descriptions, assumptions, and explanations next to executable code.
Triple-quoted strings and multi-line text
A string literal is text enclosed in quotation marks that represents a Python string value. A triple-quoted string uses three matching quote characters: three single quotes or three double quotes.
'''This is a string literal
that spans multiple lines.'''
"""This is also a string literal
that spans multiple lines."""
A standalone triple-quoted string can serve as a multi-line note in some code:
"""
This program demonstrates a greeting.
The text above is not printed by this program.
"""
print("Hello, world!")
The greeting is printed, but the triple-quoted text is technically a string literal, not a true comment. It is an expression containing a string, whereas # tells Python to ignore the rest of a physical line as a comment. Therefore, do not treat triple-quoted strings as universally interchangeable with comments.
Use consecutive # lines for ordinary source-code annotations. Use a triple-quoted string when the program genuinely needs multi-line text, or when you are writing a documentation string.
Docstrings: documentation stored in the code
A docstring is a documentation string placed in a recognized location, such as the first statement of a module, class, or function. Unlike an ordinary comment, a docstring is a string literal that Python can make available through the object's documentation attribute.
def greet(name):
"""Return a greeting for name."""
return "Hello, " + name
print(greet("Ava"))
The triple-quoted string is the function's docstring because it is the function's first statement. Tools and interactive help systems can use it to describe the function. It is not simply a discarded comment.
For example, the documentation can be read with:
print(greet.__doc__)
When documenting reusable functions, classes, or modules, a docstring is usually more suitable than a regular # comment. For nearby implementation notes, use #.
Python comment and documentation forms
| Form | Syntax | Best use | Execution behavior |
|---|---|---|---|
| # full-line comment | # explanation | A note above or beside code | Text after # on that line is ignored |
| # inline comment | statement # explanation | A short note about the statement | The code before # executes |
| Consecutive # lines | # line one# line two | A multi-line source-code explanation | Each comment line is ignored |
| Standalone triple-quoted string | """text""" | Actual multi-line text; sometimes a code note | A string literal, not a true comment |
| Docstring | def f(): """description""" | Documenting a module, class, or function | Stored as documentation for the recognized object |
Comment-writing practices
- Use clear, concise language. A reader should understand the point quickly.
- Explain reasoning. Describe why the code makes a choice, not merely what an obvious line does.
- Document assumptions and constraints. Mention required formats, limits, external behavior, or unusual conditions.
- Keep comments near the code they describe. A distant explanation is harder to connect with its subject.
- Update comments when code changes. Revise or remove a comment that no longer describes the current behavior.
- Avoid excessive comments. Too many notes can make code harder to read, especially when they restate every simple statement.
For example, this comment explains a non-obvious decision:
# Use a short timeout so a failed network request does not pause the whole program.
timeout_seconds = 5
By contrast, this comment is redundant:
# Add 1 to count
count = count + 1
The second comment may be useful for a beginner exercise, but production code usually does not need it because the statement already clearly shows what it does.
Common comment problems
Text intended as a comment causes a SyntaxError
If explanatory text is written without a leading #, Python tries to interpret it as code. If the text is not valid Python, a SyntaxError can result.
This program displays a greeting
print("Hello")
Make the explanation a comment:
# This program displays a greeting
print("Hello")
Alternatively, use a properly quoted string only when a string is actually intended.
Part of a line unexpectedly does not run
Everything after # on the physical line is treated as a comment. If the marker appears before code that should execute, that code will not run:
print("First") # print("Second")
Only First is displayed. Move the second call to its own line or place it before the comment text:
print("First")
print("Second") # This call also executes
A triple-quoted block behaves unexpectedly
Triple quotes create a string literal. Depending on its placement, the string may be a docstring or an unused string expression. Use # comments for ordinary annotations, and reserve triple-quoted strings for actual multi-line text and docstrings.
A comment no longer matches the code
This usually happens when code changes but its comment does not. Re-read nearby comments during maintenance, then update or remove any explanation that is no longer accurate.
Quick reference
- Use
#to begin a Python line comment. - A comment continues from
#to the end of the current physical line. - Code before an inline
#still executes. - Use consecutive
#lines for conventional multi-line explanations. - A triple-quoted block is a string literal, not a general-purpose comment.
- Use a triple-quoted string as a docstring when it is the first statement in a module, class, or function.
- Prefer comments that explain intent, reasoning, assumptions, or unusual behavior.