Previous Post
Python Comments: The Complete Guide (Types, PEP 8, Best Practices & Examples)
Introduction
Most developers eventually encounter the moment when they revisit their own code and realize they’ve forgotten the reasoning behind certain decisions. The logic is correct, the program works, yet the intent feels unclear. It’s a natural part of software development.
This is where comments become invaluable. They act as documentation within the code—guiding future readers, clarifying thought processes, and reducing confusion. Well-written comments don’t just explain; they preserve understanding.
In this guide, we’ll examine Python’s single-line and multi-line commenting techniques, illustrate how and when to use each one, and outline proven best practices. By the end, you’ll know how to write comments that enhance readability and support long-term maintainability.
Python Comments
In the previous post, we learned what Python comments are. A comment is a line of text in a program that is ignored by the Python interpreter. Since comments don’t affect code execution, they are mainly used as notes or explanations within the code.
In this tutorial, we’ll explore the two types of comments in Python:
- Single-line Comments
- Multi-line (pseudo) Comments
Let’s look at each type in detail with examples.
Single-line Comments in Python
A single-line comment is a piece of text in your code that begins with the hash symbol (#). Everything written after the # on that line is ignored by the Python interpreter. The comment affects only the line where the # appears, and each new line requires its own # if you want to add another comment.
Unlike languages such as C or Java, where both single-line (//) and multi-line (/* ... */) comment syntaxes exist, Python’s single-line comments don’t require an explicit closing marker because they automatically terminate at the end of the line.
Purpose of Single-Line Comments
- Code Documentation: Explain the purpose, logic, or intent of the code, making it easier for others (or yourself) to understand later.
- Debugging: Temporarily disable a line of code without deleting it, useful during testing or troubleshooting.
- Marking TODOs or Notes: Highlight tasks, reminders, or future improvements.
- Explaining Complex Logic: Clarify non-obvious code, such as algorithms or mathematical operations.
Syntax
Following is the syntax of a single-line comment.
| Syntax of a single-line comment |
|---|
| # This is a single-line comment print(‘Hello World!’) |
Comments start with #. Any text after the # will not be executed in the output.
Examples:
1. Comment placed on a new line
# Store the user age
age = 25
print(age)Single-line comments are ideal when you want to explain a specific step or provide short, clear context.
2. Commenting Out Code Using a Single-Line Comment
# print("This line is commented out and will not run.")
print("This line will execute normally.")Explanation:
- The first line starts with
#, so Python ignores it — this is how you “comment out” a line of code. - The second line runs normally and prints the output.
3. Commenting Out the Execution of Code
# The following line is commented out and will NOT execute
# result = 10 / 0 # This would cause a ZeroDivisionError
print("Program continues without running the commented-out code.")How it works
# result = 10 / 0is commented out, so Python skips it.- This prevents the code from running (and avoids the error).
- The program continues normally with the
print()statement.
4. Commenting Out a Debug Print Statement
# print("Debug: user_data =", user_data)
print("Processing completed.")5. Temporarily Disabling a Function Call
def greet():
print("Hello!")
# greet() # Disabled for now
print("Program continues...")6. Commenting Out a Line Inside a Loop
for i in range(3):
# print("Loop iteration:", i) # Disabled debug output
print(i)7. Commenting Out a Variable Assignment
# a = 42
b = 10
print(b)8. Commenting Out a Conditional Execution
is_admin = False
# if is_admin:
# print("Access granted")
print("Access denied")9. Organizing Code Into Logical Sections
# -------------------------
# 1. Import Dependencies
# -------------------------
import math
import random
# -------------------------
# 2. Define Helper Functions
# -------------------------
def calculate_area(radius):
return math.pi * radius ** 2
def get_random_number():
return random.randint(1, 10)
# -------------------------
# 3. Main Program Logic
# -------------------------
radius = 5
area = calculate_area(radius)
number = get_random_number()
# -------------------------
# 4. Output Results
# -------------------------
print("Area:", area)
print("Random Number:", number)Why this is useful
- Makes large files easier to navigate
- Groups related logic together
- Helps developers understand the code structure quickly
- Works especially well when following PEP 8 guidelines
Inline Comments (Subtype of Single-Line Comments)
An inline comment appears on the same line as a piece of code. It uses the same # symbol, but it’s placed after the statement.
Inline comments are a subtype of single-line comments.
They follow the same rules—Python ignores everything after the #.
Example:
Simple Inline Comment Example
price = 499 # Product price in USDSingle-Line + Inline Comment Together
# Calculate the total price including tax ← single-line comment
price = 100 # base price
tax_rate = 0.18 # 18% tax rate (inline comment)
total = price + (price * tax_rate) # calculate final amount (inline explanation)
print("Total:", total) # output resultWhat this example shows
- The top
# Calculate the total price…is a single-line comment describing the section. - The comments next to
tax_rateandtotalare inline comments explaining specific lines. - Both comment styles are used together in one example, demonstrating their complementary roles.
Loop Example With Both Comment Types
# Loop through numbers and print only even ones ← single-line comment
for num in range(1, 6):
if num % 2 == 0: # check if number is even (inline comment)
print(num) # print even numberFunction Example With Both Comment Types
# Function to calculate the square of a number ← single-line comment
def square(n):
return n * n # multiply number by itself (inline comment)
result = square(4) # call function
print(result) # output resultWhen to Use Inline Comments
Use inline comments when you need a short clarification about a specific part of the line. Avoid long inline comments because they can make code harder to read.
Bad Example
price = 499 # This price is set because the company decided in 2020 that...Inline comments should be short, focused, and helpful.
Multiline Comments in Python
In Python, multiline comments are used to add explanatory notes or documentation that span multiple lines in the code. However, Python does not have a dedicated syntax for multiline comments like some other languages, such as Java or C, which use /* ... */.
You can achieve multiline comments in Python using two methods:
1. Method 1: Using multiple single-line comments (#)
This is the official and recommended way according to Python’s syntax and PEP 8.
When you place several # comments one after another, many developers also refer to this style as block comments, because it creates a “block” of comments across multiple lines.
2. Method 2: Using triple-quoted string literals
These are not real comments — they are string literals.
If they are not assigned to a variable or used as a docstring, they behave like unused strings, so developers often use them as pseudo multiline comments.
This method works, but is not recommended for actual commenting because Python does not treat them as comments.
Method 1: Using multiple single-line comments (#) — also known as Block Comments
The most common way to write multiline comments in Python is to use several single-line comments in a row. You simply begin each line with the hash symbol (#). When multiple single-line comments are grouped together consecutively, they form a “block” of comments — which is why this style is often referred to as block comments.
Block comments are still a subtype of single-line comments. They are not a different syntactical construct; they are simply multiple # comment lines used together.
Block comments are ideal when:
- You need to explain a concept, not just a line
- You’re summarizing a section of code
- You’re describing logic that isn’t obvious from the implementation
Examples:
Example 1: Basic Multiline (Block) Comment
# This block of comments explains the next section of code.
# We are validating user input and checking if the age
# is within a realistic human range.
# If not, we raise a ValueError.Example 2: Describing a Section of Code
# -------------------------------
# Block comment describing a task
# This section calculates the area
# -------------------------------
radius = 5
area = 3.14 * radius ** 2
print(area)Example 3: Explaining Complex Logic
# Check if the number is prime:
# 1. Numbers less than 2 are not prime
# 2. Check divisibility from 2 to sqrt(n)
# 3. If divisible, it's not prime
num = 11
Example 4: Commenting Out Multiple Lines of Code
# The following lines are disabled
# during debugging or testing
# print("This won't run")
# print("This is also commented out")
print("Program continues...")Example 6: Long Explanatory Notes
# This block explains how user authentication works:
# - First, the system checks stored credentials.
# - Then, it validates the password hash.
# - Finally, it generates a session token.
authenticate_user()Method 2: Using Triple-Quoted String Literals (Pseudo Multiline Comments)
Python does not provide an official syntax for true multiline comments (like /* ... */ in C or Java). However, you can mimic multiline comments by creating a triple-quoted string literal that is not assigned to any variable. Because it is unused, Python parses it and then ignores it—making it behave like a “comment block.”
You can create these pseudo comments using either:
- Triple double quotes →
""" ... """ - Triple single quotes →
''' ... '''
Example: Using Triple Double Quotes
print('Multiline Comments')
"""
This is multiline comments
We are using # in each line
Multiple single-line to make multiline comment
"""Example: Using Triple Single Quotes
print('Multiline Comments')
'''
This is multiline comments
We are using # in each line
Multiple single-line to make multiline comment
'''Why This Works
- A triple-quoted string literal is created.
- It is not assigned to a variable.
- It is not used as a docstring.
- Python recognizes it, creates the string object, and then immediately discards it.
- This makes it behave like a comment, even though it’s technically not one.
Such unused string literals are considered no-ops (no operation).
Important Warning: These Are Not Real Comments
Even though this technique works, triple-quoted strings are not actual comments:
- Python still parses them (unlike real comments, which are completely ignored).
- They appear in the bytecode temporarily before being discarded.
- They should not be used as a substitute for proper comments in production code.
Example:
print('Multiline Comments')
"Unassign string"Output
Multiline CommentsThe string is ignored at runtime—but it is not a comment.
This is why Python recommends using # for actual commenting.
Docstrings vs. Pseudo Multiline Comments
Triple-quoted strings also serve a real purpose in Python:
They are used to create docstrings for modules, functions, classes, and methods.
Docstrings:
- Use triple-quoted strings (
""" ... """) - Are stored in the
__doc__attribute - Can be accessed at runtime
- Provide documentation for tools like IDEs,
help()function, etc.
Example: Docstring Demonstration
"""This is a module docstring"""
print('Multiline Comments')
print(__doc__)Output
Multiline Comments
This is a module docstringHere, the module’s docstring is printed using the __doc__ attribute.
Not an Example of Multiline Comments
Consider the following code:
x = 10
# Here x is a variable
y = 10
# Here y is a variable
z = x + y
# z consist addition of both variables
print(z)
# printing the value in the outputThis is an example of multiple single-line comments, not a true multiline comment. Each comment starts with # and is independent.
Converted into a multiline comment using triple quotes:
x = 10
y = 10
z = x + y
print(z)
'''
Here x and y are variables.
We are adding both variables and storing the result in z.
Finally, we print the value of z in the output.
'''Converted into a multiline comment using multiple #:
x = 10
y = 10
z = x + y
print(z)
# Here x and y are variables.
# We are adding both variables and storing the result in z.
# Finally, we print the value of z in the output.Both approaches work, but according to PEP 8, the second one (using multiple #) is the recommended way.
Difference in Placement of Triple Quotes
There’s a subtle difference between starting a triple-quoted string on the same line vs. on a new line.
# Same line
s1 = '''This is a multiline comment
written using
triple single quotes'''
# New line
s2 = '''
This is a multiline comment
written using
triple single quotes
'''
print(repr(s1))
print(repr(s2))Output
'This is a multiline comment\nwritten using\ntriple single quotes'
'\nThis is a multiline comment\nwritten using\ntriple single quotes\n's1has no extra newlines at the start or end.s2has a leading newline and a trailing newline.
Since we usually use triple quotes as unassigned strings for comments, this difference doesn’t affect execution. But if you ever assign the string to a variable, the extra newlines will appear.
Note: The repr() function returns the “official” string representation of an object, mainly for developers and debugging.
Single-line vs Multi-line Comments in Python
These are the following differences between single and multiline comments.
| Feature | Single-line Comment (#) | Multi-line Comment (Triple Quotes ''' / """) |
|---|---|---|
| Syntax | Starts with # | Enclosed in ''' ''' or """ """ |
| Purpose | Brief, one-line explanations | Longer explanations, spanning multiple lines |
| Runtime effect | Ignored by interpreter | Treated as a string literal, ignored if not used |
| Typical use case | Explain why code does something, inline clarification, quick TODOs | Public API documentation (docstrings) or multiline literal data; not recommended as general comments |
| Best practice | Preferred for comments; use one # per line for blocks | Use only for docstrings; avoid using as block comments in the middle of code |
| Inline use | Can appear after code on the same line | Cannot appear inline with code |
| Example | x = 5 # current value | """This function adds two numbers.""" |
Notes
- Use
#for normal comments and short block comments. - Use triple-quoted strings only for docstrings; do not rely on them as general-purpose multi-line comments.
- Keep comments focused on intent and why the code exists rather than restating what the code does.
PEP 8 Guidelines for Python Comments
PEP 8 stands for Python Enhancement Proposal 8. It’s the official style guide for Python code, created to promote readability and consistency across the Python community. It covers naming conventions, indentation, spacing, line length, and best practices for writing comments and docstrings.
The following are the key recommendations from PEP 8 for commenting in Python.
1. General Principles
- Comments should be written as complete sentences.
- Keep them up to date — outdated comments are worse than no comments.
- Use proper spelling, grammar, and punctuation.
- In multi-sentence comments, place two spaces after a sentence-ending period.
- Comments should be indented at the same level as the code they describe.
- Use block comments to explain complex code or larger sections of code.
2. Block Comments
- Explain sections of code (not just a single line).
- Each line should start with
#followed by a space. - Place them above the code they describe.
- Use full sentences and proper punctuation.
# Calculate the average score
# Exclude outliers below 0 and above 100
scores = [78, 92, 85, 63, 95]
average = sum(scores) / len(scores)
print(average)3. Inline Comments
- Placed on the same line as the code, separated by at least two spaces.
- Use them sparingly — only when the code isn’t self-explanatory.
4. Special Comments
- TODO: Mark future improvements.
- FIXME: Indicate broken or temporary code.
- NOTE: Provide additional or important information.
5. Line Length for Comments
PEP 8 specifies a 72-character limit for comments, separate from the 79-character limit that applies to code lines.
Summary
- Follow PEP 8 to keep comments consistent, clear, and professional.
- Write complete sentences with proper spelling and punctuation.
- Use block comments for larger explanations and inline comments sparingly.
- Keep comments up to date to avoid confusion.
- Respect the 72-character line length limit for comments.
- Use special tags like
TODO,FIXME, andNOTEwhen needed.
Conclusion
Writing good comments in Python isn’t just about marking up your code — it’s about communicating clearly with anyone who reads it, including your future self. Single-line comments with # are ideal for quick notes and clarifications, while triple-quoted strings should primarily be reserved for docstrings that document modules, classes, and functions.
By following PEP 8 guidelines — keeping comments concise, wrapping them at 72 characters, using proper grammar, and focusing on the why rather than the obvious what — you ensure your code stays readable, maintainable, and professional.
In the end, clean code paired with thoughtful comments turns a script into a story that’s easy to follow, debug, and improve over time. Clarity in programming isn’t just a courtesy — it’s a best practice.
Next Post
Python Comments: Frequently Asked Questions (Ultimate FAQ Guide)
Suggested Posts
1. Python Comments: The Complete Guide (Types, PEP 8, Best Practices & Examples)
2. Python Comments: Frequently Asked Questions (Ultimate FAQ Guide)

This is a really clear explanation, thank you so much for breaking down the different types of comments in Python! It’s super helpful for someone just starting out.