- Host World
- Blog
- Programming Tools
- A Practical Guide to Writing Comments in Python
A Practical Guide to Writing Comments in Python
-
8 min read
-
8
If you have ever opened an old file and thought, I know this works but I have no idea why, you already understand the real value of comments. A comment is simply a note you leave inside the code for a human reader. It is not there to make the program run. It is there to make the decision making behind the program visible. That is exactly why the question what is a comment in python matters in everyday work, not just in tutorials.
So, how to make comments in python in a way that actually helps? Python keeps it simple. Add a hash symbol and everything after it becomes explanation rather than instruction. The interpreter skips it entirely, which means you can describe intent, constraints, and reasoning without changing behavior. Used well, comments in python help future you and everyone else read the code the way you meant it to be read, with the context that usually lives only in your head.
Why Are Comments Necessary
Code is rarely written once and forgotten. It is reviewed, reused, refactored, and extended. During this lifecycle, comments in python serve as a persistent explanation of why certain decisions were made. Without them, future readers must infer intent purely from implementation, which is often unreliable.
In collaborative environments, Python comments become even more valuable. Developers reviewing unfamiliar sections rely on comments to understand assumptions, edge cases, or architectural constraints. This reduces onboarding time and lowers the risk of unintended changes.
Comments also support continuity. When original authors are no longer available, clear python comment explanations preserve institutional knowledge directly inside the codebase.
How Do Comments Help Other Developers?
Code intended for sharing should be accessible even to readers unfamiliar with the project. Comments in python provide orientation by explaining purpose, limitations, and expected behavior.
This is particularly important in team environments where multiple developers contribute asynchronously. Clear python comment usage reduces ambiguity and makes maintenance safer. Future maintainers benefit most, as they rely on comments to understand design rationale before making updates.
Reading Your Own Code Later
Revisiting code written weeks or months earlier can be surprisingly difficult. Context fades, priorities change, and design decisions may no longer be obvious. Thoughtful comments in python act as a memory aid, allowing you to quickly reconnect with your earlier thinking.
By documenting intent rather than mechanics, comments help you safely refactor or extend existing logic. This is especially important in complex systems where small changes can have wide effects. Writing clear Python comments is an investment in your future efficiency.
Comment Conventions in Python
Python style guidelines emphasize readability and consistency. While executable code lines are typically limited in length, comments should be concise and easy to scan. If an explanation requires multiple sentences, it should be split into separate comment lines.
Comments should be written as complete sentences when describing behavior or reasoning. Capitalizing the first word improves clarity. If a comment acts as an identifier or label, lowercase may be appropriate.
The goal is precision. Each comment should explain one idea clearly and only where explanation is truly needed.
What Comment Types Does Python Support
1. Single line block comments
A single line block comment appears on its own line and begins with the hash symbol. Everything after the symbol is treated as commentary until the line ends.
#!/usr/bin/python3
#This is a single-line comment describing the command below.
command
These comments are commonly used to explain the purpose of the code that follows or to separate logical sections within a file.
2. What Are Inline Comments Used For
Inline comments appear on the same line as executable code. They are typically separated from the statement by spacing to improve readability.
#!/usr/bin/python3
for x in[1, 2, 3]: # This is an inline comment.
Inline comments should be used sparingly. Overuse can reduce readability and make lines visually cluttered.
3. How Multi Line Comments Work in Python
Python does not provide a dedicated syntax for multi line comments. Instead, developers combine multiple single line comments to form a logical block.
#!/usr/bin/python3
#This is a multi-line comment. Each sentence in a multi-line
#comment (or, block comment") should begin with a capital letter
#and should end with a period.
#
#The Python style guide suggests all comments should be sentences
#that are easily read by second-language English readers.
#
#New paragraphs in a block comment should be separated by the "#"
#character on a line by itself.
#
#Although comments can exceed 72 characters (some interpreters
#allow comments to be of any line length), for improved readability
#and portability, comments should not exceed 72 characters.
for i in [1, 2, 3]:
print(i)
This approach maintains consistency and avoids ambiguity while allowing longer explanations.
Documentation Strings Explained
Python supports documentation strings, commonly known as docstrings. A docstring is a string literal placed immediately after a module, class, or function definition. It describes what the object does rather than how it does it.
Docstrings differ from standard comments because they are accessible at runtime and can be extracted by documentation tools. They are especially useful for python function comments intended to describe inputs, outputs, and behavior.
#!/usr/bin/python3
def stuff(a, b):
result = a * b
"""
Here, we define the sum
of the result
to use in function x().
"""
return result
Placement matters. When a string appears directly after a definition, Python interprets it as a docstring rather than a regular comment.
Docstrings integrate with the built in help system and the doc attribute, enabling interactive documentation.
What Types of Docstrings Exist
There are two common docstring formats.
One liner docstrings summarize simple behavior.
Multi line docstrings include a short summary followed by detailed descriptions of parameters and return values.
For docstrings, triple double quotes must always be used.
def greet(name):
"""Return a greeting for the given name with newlines."""
return f"\nhello, { name } \n"
#The tradition of using "hello, world" in program examples
#became popularized in the 1970s by Dennis Kernigham.
print(greet("world"))
def total_cars(GM, Ford, Chevy):
"""
This function calculates the total number of cars
from three different car manufacturers.
Args:
GM (int): The number of cars from GM.
Ford (int): The number of cars from Ford.
Chevy (int): The number of cars from Chevy.
Returns:
int: The total number of cars from all three brands.
"""
Recommended Practices for Commenting Python Code
Effective comments focus on intent rather than repetition. Code already shows how something works. Comments should explain why the code exists or why a particular approach was chosen.
Avoid redundant comments that restate obvious behavior. Clear naming conventions often eliminate the need for excessive annotation.
Writing Comments for Yourself
Personal comments can serve as reminders about context, conventions, or external references.
#Most recent version of our output.csv specification is found at
#https://bit.ly/3mH5y5f4Zz
import csv
with open('input.csv', newline='', encoding='utf-8') as f:
[...]
They can also document intentional deviations from your usual style.
## noteToSelf: I would normally use SCREAMING_SNAKE_CASE
## for constants but need to remember this client prefers
## lowerCamelCase
Writing Comments for Other Developers
When code is shared, comments should anticipate future questions. Explain non standard behavior and reference authoritative sources where relevant.
#This code is based on the example from the Python documentation:
#https://docs.python.org/3/library/csv.html#csv.DictWriter
import csv
with open('output.csv', 'w', newline='') as csvfile:
[...]
Comments are especially important when fixing bugs or introducing constraints.
##NOTE: Because of issues with a downstream consumer,
##we now have to sanitize all output, removing any null
##characters and any trailing spaces.
name = name.replace('\x00', '').rstrip()
#NOTE: Some function names deviate from Python's recommended
#naming conventions because LEGACY. Python conventions would prefer
#something like "total_financial" or "sum_financials" but legacy
#support for some FORTRAN from Plethos Wealth dictates otherwise.
def TOT_FINS(financials, external):
[...]
Comment Practices to Avoid
1. Why are emotional comments harmful?
Comments should remain professional. Personal criticism or frustration has no place in production code.
def dotexas(income):
# UGH! This original code was so bad, it's giving me a headache!
# Whoever coughGERALDcough wrote this should be fired.
taxes = 0.09*pay
[...]
A neutral explanation is always preferable.
def calc_tax(income):
# Calculates the tax owed based on income and tax rates
tax_rate = CITY_TAX*pay
[...]
2. Why do vague comments reduce clarity?
Comments should be precise and informative.
#This function will do some stuff for Bob
def func(some_var):
stuff = some_var * 2
return stuff
Clear intent improves maintainability.
#Doubles the input number and returns the result
def double(number_to_double):
result = number_to_double * 2
return result
3. How much commenting is enough?
Too many comments can clutter code, while too few leave readers guessing. Aim for balance.
def even_list(input_list):
# Initialize an empty list to hold the even numbers
output_list = []
# Iterate over the input list and save the even elements
for element in input_list:
if element % 2 == 0:
output_list.append(element)
return output_list
Conclusion
Comments rarely save a bad design, but they often save good code from being misunderstood. The most valuable comments in python are not summaries of what the line does, they capture decisions that the code itself cannot express: why a shortcut was taken, which constraint shaped the solution, what must not change, and what a future refactor should aim for. That is where comments in python pay for themselves.
A practical test is maintenance pressure. When a bug arrives at 2 a.m. or a teammate needs to change behavior without breaking contracts, high quality Python comments reduce guesswork and prevent accidental rewrites of intentional behavior. Poor comments do the opposite, they create confidence where it is not deserved, especially when they drift out of sync with the code.
Treat comments in python as part of the interface, not decoration. Write them where a reader would otherwise need a meeting, a ticket, or a long dive through history to understand what is safe to change. When a comment no longer describes the truth, remove or replace it quickly, because an incorrect comment is more expensive than no comment at all.
Leave your reviewsShare your thoughts and help us improve! Your feedback matters to us