comment
Comments are explanatory text that Python ignores when executing code. They help make code more readable and maintainable.
Single-Line Comments
- Start with a hash symbol (
#
) - Python ignores everything after the
#
on that line
Python
# This is a single-line comment
x = 5 # This comment is after some code
# You can use multiple single-line comments
# to explain something over several lines
# like this
Triple-Quoted Strings
- While Python doesn’t have true multi-line comments, triple-quoted strings (
'''
or"""
) are often used similarly - Typically used for documentation strings (docstrings)
Python
def calculate_area(radius):
"""
This is a docstring - a special type of multi-line comment
that describes what a function does
Args:
radius: The radius of the circle
Returns:
The area of the circle
"""
return 3.14 * radius * radius
Commenting Best Practices
- Write clear, concise comments that explain “why” rather than “what”
- Keep comments up-to-date with code changes
- Use comments to explain complex logic or important decisions
- Avoid obvious comments that just restate the code
Related Resources
Tutorial
Writing Comments in Python (Guide)
Learn how to write Python comments that are clean, concise, and useful. Quickly get up to speed on what the best practices are, which types of comments it's best to avoid, and how you can practice writing cleaner comments.
For additional information on related topics, take a look at the following resources:
- Documenting Python Code: A Complete Guide (Tutorial)
- Writing Comments in Python (Course)
- Documenting Code in Python (Course)
- Documenting Python Code: A Complete Guide (Quiz)
By Dan Bader • Updated Jan. 8, 2025