As your code grows, it stops being obvious at a glance why a particular line exists or what a function is meant to do. Comments let you leave notes directly inside your source code that Python completely ignores when running the program — they exist purely for the humans reading the code, including your future self.
Single-Line Comments
A single-line comment starts with a # symbol. Everything after it, to the end of that line, is ignored by Python:
# This program calculates the area of a rectangle
width = 10
height = 5
area = width * height # multiply width by height
print(area)
Output:
50
Comments can sit on their own line, or trail at the end of a line of code, as shown above. Good comments explain why something is done a certain way, not just what the code does — the code itself already shows what it does.
Multi-Line Comments
Python has no dedicated multi-line comment syntax, but a common workaround is a triple-quoted string that isn't assigned to anything — Python evaluates it and discards it:
"""
This section handles user authentication.
It checks the username and password against
the stored records before granting access.
"""
print("Checking credentials...")
Output:
Checking credentials...
This works, but it's technically a string literal, not a true comment — which is exactly why Python repurposes this same syntax for something far more useful: docstrings.
Docstrings
A docstring is a triple-quoted string placed as the very first statement inside a function, class, or module. Unlike a regular comment, Python actually stores a docstring and makes it accessible at runtime through the built-in __doc__ attribute — tools and code editors use this to show documentation automatically.
def calculate_area(width, height):
"""Return the area of a rectangle given its width and height."""
return width * height
print(calculate_area(4, 5))
print(calculate_area.__doc__)
Output:
20
Return the area of a rectangle given its width and height.
This is why docstrings matter more than ordinary comments once you start writing functions: calling help(calculate_area) in the Python shell, or hovering over the function name in most code editors, displays this exact docstring to anyone using your function — including you, months later.
Comment Best Practices
- Keep comments up to date — an outdated comment that contradicts the code is worse than no comment at all.
- Avoid stating the obvious, like
# add 1 to xabovex += 1. - Use docstrings for anything another developer (or you, later) would need to call correctly — function parameters, return values, and any non-obvious behavior.
With comments and documentation covered, it's time to look at how Python actually performs calculations and comparisons, starting with Python operators.
