1.12. Describing Code#
Comments help explain what your code does and why. In Python, anything following a #
on a line is a comment and is ignored by the interpreter. The #
can appear anywhere on a line, but it does not create a comment inside a string literal.
Example:
x * (x + 1) # This is a secret formula
1.12.1. Multiline comments#
Python has no dedicated multiline comment syntax. Triple-quoted strings ('''...'''
or """..."""
) can span multiple lines, but they are strings, not comments. When placed as the first statement in a module, class, or function, they become docstrings; elsewhere, they are still real string objects and may consume memory.
Examples (not true comments):
"""
This spans multiple lines.
If placed at the top of a module/function/class,
it is a docstring, not a comment.
"""
x * (x + 1)
'''
This also spans multiple lines,
but it’s still a string literal, not a comment.
'''
x * (x + 1)
1.12.2. Best practice#
Use
#
for comments—even when they span multiple lines—by prefixing each line with#
. This is unambiguous and cannot be mistaken for a docstring or a string literal.
Example:
# This is a multiline comment.
# It spans multiple lines.
x * (x + 1)
Reserve triple-quoted strings for actual docstrings that document modules, classes, and functions:
def area(radius: float) -> float:
"""Compute the area of a circle with the given radius."""
from math import pi
return pi * radius * radius