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.
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.
# This entire line is a comment.
x = 10 # This is an inline comment, explaining the code on the left.
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 ''').
"""
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.
'''
__doc__ attribute of a function or class and can be accessed programmatically at runtime (e.g., using the help() function).PEP 8 (Python Enhancement Proposal 8) is the official style guide for Python code. It provides important recommendations for writing clear comments:
# (e.g., # This is correct).