Table of Contents
What Will You Learn
This guide explains how to use comments effectively in Python to document code, improve readability, and collaborate with other developers. You’ll
learn the difference between single-line and multi-line comments, and when to use each one.
Comments are an integral part of quality code. They do not affect the execution of the program, but serve as a vital means of communication between developers. A well-written comment helps quickly understand what a particular part of the code does, especially when revisiting it months later. In Python, commenting is implemented simply, but it requires discipline and an understanding of standards.
What are Comments in Python?
In Python, comments are used to explain code, disable temporary logic blocks, and document functions. There are three main types:
Comment Type | Description | How to Use |
---|---|---|
Block comments | Placed above a block of code. They explain what an entire section of the program does. | Each line starts with # . Used to describe the purpose or logic. |
Inline comments | Written on the same line as the code. They explain a specific action or value. | Placed after the code, begin with # , and are separated by two spaces. |
Multiline comments | Used for extended explanations or to temporarily disable blocks of code. | Formatted as multiple lines with # or enclosed in ''' / """ . |
Comments should be concise, accurate, and truthful. Avoid stating the obvious, but make sure to explain anything non-standard or potentially confusing.
Python Block comments
Python block comments are comments placed above a logical block of code to explain its purpose. Each block comment consists of one or more lines starting with the
#
symbol. They help describe the general meaning of the following code — why it’s there, what problem it solves, and what it affects. This format of commenting makes
the program’s structure clearer and improves code readability.
Block comments are especially useful when working with functions, loops, or conditionals where understanding the context is important.
How to Make Block Comments in Python?
To create a block comment, simply put #
in front of each line:
# Check if the user is authenticated
# If not — redirect to the login page
if not user.is_authenticated:
redirect_to_login()
These comments should be aligned with the code and written in a clear, affirmative style — brief and to the point.
Python Inline Comments
Python inline comments are comments placed on the same line as the code. They are used to explain individual operations, variables, or non-standard solutions directly in context.
They start with the #
symbol and are written to the right of the expression they refer to. These comments should be brief, useful, and not state the obvious.
Inline comments make code easier to understand without scrolling up to a block explanation.
Inline comments are placed on the same line as the code, usually to the right. They are used to explain specific actions or values:
total = price * quantity # calculate the total order amount
It's important that an inline comment starts with at least two spaces after the code and provides actual value. Avoid stating the obvious:
x = 5 # assign 5 to variable x ← redundant
Python Multiline Comments
Multiline comments are used when a single-line explanation is not enough. They are useful if you want to describe a function’s logic in detail, explain a complex part of an algorithm, leave internal instructions for the team, or temporarily disable multiple lines of code.
Python does not have a specific syntax for multiline comments like /* */
in JavaScript or C. Instead, you can use either multiple lines starting with #
,
or triple quotes ('''
or """
) to create a multiline string, which the interpreter ignores if not assigned to a variable or used as a docstring.
How to Make Multiline Comments in Python?
There are two ways:
-
Multiple lines starting with
#
:
# This function calls the API
# Processes the result and saves it to the database
# Used in the data synchronization module
-
Triple quotes
'''
or"""
— technically not comments, but often used as such:
'''
This block is temporarily disabled.
Output formatting needs to be updated for the new spec.
'''
# do_something()
Important: Triple quotes create a string that is ignored by the interpreter if not assigned to a variable. Inside functions, they may be interpreted as docstrings.
How Can I Remove Comments From a Python Script?
Removing comments may be necessary for various reasons: preparing code for publication, exporting to a production server, minimizing file size, or cleaning up outdated notes. It's important to understand: comments don't affect program execution but may contain outdated or sensitive information, especially in test or local versions of scripts.
There are several ways to remove comments from a Python script:
1. Manually. Suitable for small files. Simply go through each line and delete anything that starts with #
(or the whole line if it's a full
comment). Also remove blocks enclosed in '''
or """
if they are used as comments and not as docstrings.
2. Using editor shortcuts. Many IDEs allow quick comment removal:
- VS Code:
Ctrl + Shift + L
+Ctrl + /
— select all comments and remove them. -
PyCharm:
Ctrl + /
— toggles a comment on/off.
However, this only works with visual selection — manual review is still necessary.
3. Automatic removal via script. You can write a Python script to open the target .py
file and remove all lines containing #
, as well
as ignored blocks in triple quotes. Example:
def remove_comments(file_path):
with open(file_path, 'r') as f:
lines = f.readlines()
cleaned = []
inside_block = False
for line in lines:
if '"""' in line or "'''" in line:
inside_block = not inside_block
continue
if inside_block:
continue
if line.strip().startswith('#'):
continue
if '#' in line:
line = line.split('#')[0].rstrip() + '\n'
cleaned.append(line)
with open("cleaned_" + file_path, 'w') as f:
f.writelines(cleaned)
4. Using third-party tools. There are tools for automatic code formatting that can be configured to remove comments:
black
— formats code but does not remove comments.autopep8
— same.- To remove comments — write your own preprocessor or use
sed
,awk
,grep
(Linux/Mac).
Important: if your code includes docstrings used for documentation, blindly removing lines with triple quotes can result in the loss of valuable information. Always back up the file before removing comments.
Python Docstrings
A docstring (documentation string) is a special type of string used to document code. Unlike regular comments (#
), a docstring is stored in the
object and accessible at runtime. It appears when calling help()
or accessing the .__doc__
attribute.
Docstrings are used for:
- functions;
- class methods;
- classes themselves;
- modules (at the top of the file).
Example:
def divide(a, b):
"""
Divides number a by b and returns the result.
Returns None if b equals 0.
"""
if b == 0:
return None
return a / b
You can access this text like so:
print(divide.__doc__)
Docstring Style
Python supports several documentation formats:
- PEP 257 — the official Python standard for docstrings;
- reStructuredText — often used with Sphinx (for generating documentation);
- Google style — used in Google open-source projects;
- NumPy/SciPy style — popular in scientific libraries.
PEP 257 recommends:
- Start with a brief one-line summary.
- If more explanation is needed — add a blank line and an extended description.
- Describe parameters and return values.
- Use triple double quotes
"""
, not single quotes.
Example of an extended docstring:
def login(user, password):
"""
Verifies user login and password.
Args:
user (str): Username.
password (str): Password.
Returns:
bool: True if authentication is successful, otherwise False.
"""
...
Why Use Docstrings?
- Make code easier to understand.
- Improve documentation quality.
- Simplify working with libraries and APIs.
- Are automatically used in help generation and documentation tools.
Important: a docstring is not a comment. It is part of the object. It should not be used to disable code or leave temporary notes — use
#
for that.
Common Beginner Mistakes
1. Too Many or No Comments
What happens:
Beginners often go to extremes. Some comment every single line, even obvious actions like variable assignments or function calls. Others leave no explanation at all, even when
the logic is complex and unclear.
Why it’s a mistake:
Excessive comments clutter the code and make it harder to read. Lack of comments makes understanding the intent difficult. Good comments are needed when logic isn’t obvious, a
non-standard approach is used, or architectural compromises are made.
How to do it right:
Write comments only when they truly add value. Don’t state what’s already obvious from the code. Don’t write: x = 5 # assign 5 to variable x
. Better:
MAX_RETRIES = 5 # Maximum number of retry attempts
.
2. Comments Don’t Match the Code
What happens:
The code changes, but the comment stays the same. For example, a comment says a GET request is used, but the code now uses POST. Or it claims a variable holds a list, but it’s
actually a dictionary.
Why it’s a mistake:
Mismatched comments are misleading. They're worse than no comment at all because they create a false sense of understanding. These errors are especially risky in large teams or
when maintaining someone else’s code.
How to do it right:
Always update comments when changing code. Use editors and plugins that highlight outdated comments. Ideally, a comment should be so accurate you can fully rely on it.
3. Using Triple Quotes Outside of Docstrings
What happens:
Some beginners use """
or '''
to write multiline comments outside of functions or classes, thinking it’s a convenient way to comment out a block of
text.
Why it’s a mistake:
These strings are interpreted by Python as actual string objects, not comments. If not assigned to a variable, they still occupy memory (until garbage collected) and may be
treated as docstrings — especially if placed at the start of a file or function.
How to do it right:
Use #
for all types of comments except when documenting functions and classes. For multiline explanations, place #
before each line. Use triple quotes
("""
) only for docstrings, following the PEP 257 standard.
4. Poorly Written Comments
What happens:
Comments are written carelessly, using slang, with grammar mistakes, incomplete thoughts, or completely off-topic. For example:
# messed something up here, will fix later
.
Why it’s a mistake:
A comment is just as much a part of the code as any logical line. It should be written professionally, clearly, and with respect for the future reader (including yourself in a
month).
How to do it right:
Write comments thoughtfully and to the point. Use a professional and neutral tone. A comment should add understanding, not raise questions. Better:
# Convert dates to YYYY-MM-DD format
, instead of # kinda converted it, should be fine
.
5. Disabling Code with Comments Instead of Using Git
What happens:
To “temporarily” disable a block of code, beginners often comment out 10–15 lines. These fragments often remain in the project forever, forgotten and cluttering the code.
Why it’s a mistake:
Comments are not meant for storing old code. This clutters the project, increases the risk of conflicts, and breaks structure. Comments should clarify — not hide logic.
How to do it right:
Use version control (like Git). If you need to temporarily disable code — create a separate branch, commit the current version, and remove the unnecessary block. This way you can
always go back to it without cluttering your main file.
Comments are not a formality, but a practical tool. Well-written comments make your code clearer and more reliable.
Frequently Asked Questions
How to do comments in Python?
To write a comment, start the line with the #
symbol. Everything after #
will be ignored by the interpreter. Comments can be written on a separate
line (block comment) or at the end of a line of code (inline comment). For documenting functions and classes, use docstrings — multiline strings inside triple quotes.
What is the character that inline Python comments begin with?
Inline comments in Python begin with the #
symbol. Everything following it is ignored by the interpreter. Symbols like %
, -
, or
"
are not used for commenting in Python. Only #
is considered syntactically valid for comments.
What symbol is used for comments in Python?
Python uses only one symbol for comments — #
. It is used for both single-line and multiline comments (by repeating #
on each line).
For documenting functions and classes, use triple quotes ("""docstring"""
), which are considered docstrings, not regular comments.
How to turn multiple lines into comments in Python?
You can place #
before each line or select the lines in an editor and use a shortcut (e.g., Ctrl + /
in VS Code or PyCharm). You can also use triple
quotes '''
or """
— but only if those strings will not be interpreted as part of the logic. They are suitable for temporarily disabling blocks or for
explanations.
What is the difference between a comment and a docstring in Python?
A comment (#
) is for the programmer. It explains the logic and is not included in documentation. A docstring ("""text"""
) is a special documentation
string embedded in the object itself. It can be accessed programmatically via .__doc__
. Comments explain code, while docstrings are part of the official
documentation for functions, classes, and modules.