Comments are lines that Python ignores entirely when it runs your program. They exist for people — to explain what code does, why a decision was made, or to temporarily disable a line during debugging. Learning to write comments well is one of the first habits that separates readable code from code that confuses everyone, including the person who wrote it six months later.
Python's comment syntax is intentionally minimal. There is one comment character — the hash symbol (#) — and it applies to everything from that point to the end of the line. That simplicity makes comments easy to learn but easy to misuse. This tutorial covers single-line comments, inline comments, block comments, and docstrings, along with the PEP 8 style guidelines that govern when and how to use each one.
What Is a Comment in Python?
A comment is any text in a Python source file that begins with the # character, excluding # characters that appear inside string literals. When the Python interpreter reads a file, it discards everything on a line from the # onward before any execution takes place. The comment text never becomes part of the compiled bytecode.
The practical consequence is straightforward: comments carry zero runtime cost and produce no side effects. They exist purely in source code for human readers. This makes them the right place for intent, context, and warnings — information that does not belong in the logic itself.
A # inside a string literal is not a comment. tag = "#python" stores the string #python. The hash only triggers comment behavior when it appears outside of any string.
# This entire line is a comment — Python ignores it completely
print("Hello") # Only the text after # is a comment here
tag = "#python" # The # inside the string is NOT a comment
hashtag = '#' + 'py' # Also not a comment — it is inside a string
Build a valid single-line comment that reads: # Store the user's age
Types of Comments in Python
Python has one comment character but several patterns of use. Each pattern serves a different purpose, and choosing the right one keeps your code readable without adding clutter.
Single-Line Comments
A single-line comment occupies its own line, placed above the code it describes. This is the standard way to explain what a block of logic does or why a particular approach was chosen. PEP 8 recommends starting comment text with a capital letter and writing in complete sentences where practical.
# Calculate the area of a rectangle
width = 10
height = 5
area = width * height
# Using integer division to avoid floats in the result
pages = total_words // words_per_page
Inline Comments
An inline comment sits at the end of a line of code. PEP 8 requires at least two spaces between the statement and the #, and one space after the #. Inline comments should be used sparingly. When the code is self-explanatory, an inline comment just creates noise.
MAX_RETRIES = 3 # Network requests only — not for file I/O
timeout = 30 # Seconds before connection is dropped
x = x + 1 # Good: non-obvious increment reason goes here
y = y + 1 # Bad: no information added — remove this one
If you catch yourself writing an inline comment to explain what a variable name means, rename the variable instead. A name like conn_timeout_sec removes the need for the comment entirely.
Block Comments (Multi-Line)
Python has no dedicated multi-line comment syntax. When you need to write a longer explanation that spans multiple lines, the standard approach is to put a # at the start of each line. Each line in a block comment should be indented to match the code it sits above.
# Validate the user-supplied email address before sending a
# confirmation link. The regex below follows RFC 5322 loosely;
# it catches the most common formatting errors without being
# brittle against edge-case valid addresses.
import re
def is_valid_email(address):
pattern = r'^[^@\s]+@[^@\s]+\.[^@\s]+$'
return bool(re.match(pattern, address))
- Syntax
# Your comment text here— placed on its own line above the code it describes.- Best used for
- Explaining the intent of a block of code, noting a non-obvious decision, or flagging a TODO item.
- Syntax
statement # comment text— two spaces before#, one space after.- Best used for
- Clarifying a specific value or flag whose meaning is not obvious from the name alone. Use sparingly.
- Syntax
- Consecutive lines each starting with
#, indented to the same level as the surrounding code. - Best used for
- Longer explanations, algorithm descriptions, or context that does not fit on a single line.
One line below has a comment syntax error. Click the line you think is wrong, then hit check.
// to #. Python uses # for comments. The // syntax is used in languages like JavaScript and C, but in Python it is the floor division operator — placing it at the start of a line without operands causes a SyntaxError.
Docstrings vs. Comments
Docstrings are often confused with comments, but they are fundamentally different. A docstring is a string literal — enclosed in triple quotes — placed as the first statement inside a function, class, method, or module. Because it is a string, not a comment, Python stores it on the object's __doc__ attribute at runtime. IDEs, the built-in help() function, and documentation generators like Sphinx all read it from there.
Comments, by contrast, are stripped out before the code ever runs. They cannot be read programmatically. The practical rule is simple: use docstrings to document the interface of something (what it accepts, what it returns, what it does), and use comments to explain the internal reasoning of the implementation.
def celsius_to_fahrenheit(celsius):
"""Convert a Celsius temperature to Fahrenheit.
Args:
celsius (float): Temperature in degrees Celsius.
Returns:
float: Equivalent temperature in degrees Fahrenheit.
"""
# Multiply first, then add — avoids a separate variable
return (celsius * 9 / 5) + 32
# Access the docstring at runtime
print(celsius_to_fahrenheit.__doc__)
Triple-quoted strings that are not the first statement in a function or module are just regular string literals, not docstrings. They are still ignored by the interpreter if not assigned, but they are not stored as __doc__ and should not be used as a substitute for block comments.
How to Write Comments in Python
The steps below walk through each comment type in practical order, from the syntax to the style decisions that keep comments useful rather than cluttered.
-
Write a single-line comment
Type the
#character, followed by a single space, then your comment text. Place the line directly above the code it describes, at the same indentation level. Start with a capital letter and write a complete thought. Example:# Normalize scores to a 0–1 range before plotting -
Add an inline comment when the code alone is not clear
After a statement, add at least two spaces, then
#, then one space, then your comment. Reserve inline comments for values or flags whose purpose is genuinely non-obvious. If you can rename the variable to eliminate the need for the comment, do that instead. -
Use consecutive # lines for longer explanations
When context requires more than one sentence, start each line with
#and a space. Keep each line to roughly 72 characters (PEP 8's recommended limit), and indent all lines to match the surrounding code. Do not use triple-quoted strings as a substitute for block comments. -
Write a docstring to document a function or class
Place a triple-quoted string as the very first statement inside a
deforclassblock. Describe what the function does, its parameters, and its return value. Do not describe the implementation — that belongs in inline or block comments inside the body. -
Apply PEP 8 comment style consistently
PEP 8 specifies: block comments start with
#(hash plus space); inline comments use at least two spaces before#; comment text begins with a capital letter; and comments should be complete sentences where practical. Consistent style makes code easier to scan for documentation versus logic.
"Code is read much more often than it is written." — Guido van Rossum
Python Comments: Key Takeaways
- Python uses
#as its only comment character. Everything after#on a line is ignored by the interpreter — unless the#appears inside a string literal. - There are three common comment patterns: single-line (above a block), inline (end of a statement), and block (multiple consecutive
#lines). Python has no dedicated multi-line comment syntax. - Docstrings are not comments. They are triple-quoted string literals stored as
__doc__at runtime, used to document functions, classes, and modules. Use comments to explain how; use docstrings to explain what. - PEP 8 recommends capitalizing comment text, keeping inline comments sparse, and maintaining indentation parity between comments and the code they describe.
- Good comments explain intent and non-obvious decisions — not mechanics that the code already makes clear. If a comment just repeats what the code says, it adds noise and should be removed.
Writing clean comments is a habit that compounds. A codebase with accurate, purposeful comments stays navigable as it grows. A codebase with stale or redundant comments becomes actively misleading. The goal is not maximum comment density — it is maximum clarity.
Frequently Asked Questions
Use the hash symbol (#) to write a comment in Python. Anything after # on that line is ignored by the interpreter. For example: # This is a comment. The # can appear at the start of a line or after a statement for an inline comment.
Python does not have a dedicated multi-line comment syntax. Programmers commonly use consecutive single-line comments with # on each line. Triple-quoted strings are sometimes used informally but are string literals, not true comments, and are not recommended as a multi-line comment substitute.
A docstring is a string literal that appears as the first statement inside a function, class, or module. It is enclosed in triple quotes and is accessible at runtime via the __doc__ attribute. Docstrings document what a piece of code does, not how it works internally.
A comment uses # and is stripped out entirely by the Python interpreter — it has no runtime presence. A docstring is a string literal stored on the __doc__ attribute and can be read programmatically by tools and IDEs. Use comments for internal implementation notes; use docstrings to document the public interface.
Yes. An inline comment is placed on the same line as a statement by adding a # after the code. PEP 8 recommends at least two spaces before the # and one space after it. Inline comments should be used sparingly and only when they add information that the code itself does not make clear.
Yes. A # character inside a string literal — single-quoted, double-quoted, or triple-quoted — is treated as part of the string, not as a comment marker. For example: tag = '#python' stores the string #python without any comment behavior.
PEP 8 recommends that comments be complete sentences starting with a capital letter, that block comments match the indentation of the code they describe, and that inline comments use at least two spaces before the # marker. Inline comments should be used sparingly and avoided when the code is already clear.
Comments themselves are not interpreted by Python at all, so case has no technical significance inside a comment. Any code that appears before the # on the same line is still case-sensitive and executed normally.