1. Single-Line Comments
Use the #
symbol to write a comment on a single line.
# This is a single-line comment
x = 5 # This is an inline comment
2. Multi-Line Comments (Using #
)
Although Python doesn’t have a built-in multi-line comment syntax, you can use #
at the beginning of each line.
# This is a multi-line comment
# that spans multiple lines
# using the hash symbol.
3. Multi-Line Comments (Using Triple Quotes)
Triple quotes ('''
or """
) are often used for docstrings but can also be used as multi-line comments.
"""
This is a multi-line comment
using triple double-quotes.
"""
'''
This is another way to write
multi-line comments.
'''
Note: Triple-quoted comments are technically strings, but if not assigned to a variable, they are ignored by Python.
4. Docstrings (Documentation Strings)
Docstrings describe modules, functions, classes, or methods.
def add(a, b):
"""This function adds two numbers and returns the result."""
return a + b
To view a function’s docstring:
print(add.__doc__)
5. Commenting Out Code
You can use comments to temporarily disable lines of code.
x = 10
# y = 20 # This line is ignored
print(x)
6. Using Comments for Debugging
You can comment out different parts of your code to isolate issues.
x = 5
# print(x + 2)
print(x * 2) # Debugging different outputs
7. Best Practices for Comments
- Keep comments concise and meaningful.
- Use comments to explain why, not what.
- Avoid obvious comments.
- Use docstrings for functions, classes, and modules.
- Keep comments updated when code changes.
Example of a well-commented function:
def calculate_area(radius):
"""Returns the area of a circle given its radius."""
pi = 3.14159 # Approximate value of π
return pi * (radius ** 2)