You need to use comments. It's not optional if you want to write good code. Hereβs how and why.
What Are Comments?
Comments are lines in your code that Python ignores.
Their purpose is for humans. They explain what your code does or why you did something.
How to Write Comments
There are two main ways.
1. Single-Line Comments
Use the hash symbol (#
). Anything after the #
on that line is ignored.
# This entire line is a comment.
x = 10 # This part is a comment. The code before it runs.
Use this for short explanations of a single line or a small block of code.
2. Multi-Line Comments (Docstrings)
Use triple quotes ("""
or '''
).
"""
This is a multi-line comment.
You can write as much as you want here.
It's good for explaining complex functions or files.
"""
def my_function(arg1):
'''You can also use single quotes like this.'''
return arg1 * 2
Technically, these are "docstrings." They are used to document functions, classes, and modules. But many use them for regular multi-line comments. It works.
Why You MUST Use Comments
Explain the "Why," Not the "What": Your code shows what it's doing. A good comment explains why it's doing it that way.
# Bad comment:
i = i + 1 # Increment i by 1
# Good comment:
# We need to skip the first element because it's a header.
if i > 0:
process_data(row)
Help Your Future Self: You will forget why you wrote that weird piece of code six months from now. Your future self will thank you for leaving a comment.
Help Other Developers: Anyone else who reads your code needs to understand it. Clean code is important, but comments fill in the gaps.
Commenting Out Code: Use comments to temporarily disable code for testing. Don't delete it. Just comment it out.
# x = get_data_from_slow_api()
x = get_test_data() # Use this for now to speed up testing.
Rules for Good Comments
- Don't state the obvious. Commenting
x = 5 # sets x to 5
is useless and adds noise. - Keep them updated. An outdated comment is worse than no comment. If you change the code, change the comment.
- Be concise. Get to the point. No one wants to read a novel.
Bad code with comments is still bad code. Write clear code first, then add comments where necessary to explain the complex parts.