Python Comments

Python comments are "non-executable lines of text" within code that are used to explain what the code does. They are completely ignored by the Python interpreter during execution.

Comments are essential for writing "clean, readable, and maintainable code" that other programmers (and your future self!) can easily understand.


1. Single-Line Comments

The most common way to create a comment is by using the "hash symbol" (#). Everything following the # on that line is treated as a comment.

Syntax

# This entire line is a comment.

x = 10  # This is an inline comment, explaining the code on the left.

Purpose


2. Multi-Line Comments (Docstrings)

While Python doesn't have a dedicated syntax for multi-line comments, developers use "docstrings" for this purpose. Docstrings are documentation strings enclosed in triple quotes (""" or ''').

Syntax

"""
This is a docstring.
It spans multiple lines and is primarily used
to document a function, class, or module.
"""
def add_numbers(a, b):
    # ... function code here
    return a + b

Using single quotes works the same way:

'''
This also works as a docstring.
'''

Purpose of Docstrings

Style Tip (PEP 8): Triple quotes used *outside* a function or class definition are technically just multi-line string literals that are ignored, effectively serving as a comment. If they are the *first* statement inside a function or class, they become an official docstring.

PEP 8 Guidelines for Comments

PEP 8 (Python Enhancement Proposal 8) is the official style guide for Python code. It provides important recommendations for writing clear comments: