Single-Line Comments
Any text after a # symbol on a line is a comment. Python ignores everything from the # to the end of that line.
# This is a full-line comment
print("Hello") # This is an inline comment
# Multiple single-line comments:
# Step 1: Get user input
# Step 2: Validate it
# Step 3: Process it
Multi-Line Comments (Triple Quotes)
Python doesn't have a dedicated multi-line comment syntax. The convention is to use triple-quoted strings (they are technically string literals that get assigned to nothing, so Python ignores them).
"""
This is a multi-line
"comment" using triple quotes.
Python evaluates it as a string but discards it.
"""
print("Code continues here")
Docstrings β Documentation Strings
Docstrings are triple-quoted strings placed as the first statement in functions, classes, or modules. Unlike regular comments, docstrings are accessible at runtime via .__doc__ and are used by documentation generators.
def calculate_area(radius):
"""
Calculate the area of a circle.
Args:
radius (float): The radius of the circle.
Returns:
float: The area of the circle.
"""
import math
return math.pi * radius ** 2
print(calculate_area(5))
print(calculate_area.__doc__)
When to Write Comments β Best Practices
Comments should explain WHY, not WHAT. Well-named code explains itself. Only add comments when the reasoning is not obvious.
# β Useless comment - the code already says this
x = x + 1 # increment x by 1
# β
Useful comment - explains non-obvious behavior
x = x + 1 # Offset by 1 to convert 0-based index to 1-based display
# β
Useful: explains a workaround
# Using int() instead of round() here because the legacy API
# expects truncated values, not rounded (see ticket #1234)
result = int(value)
The best code requires no comments because variable and function names make the intent clear. Aim for self-documenting code first, comments second.