In Python, comments are used to explain or annotate code. They are ignored by the Python interpreter and are solely for human readers. There are two types of comments in Python:
Types of comments
1. Single-line Comments
- Use the
#
symbol to create a single-line comment. - Everything after the
#
on that line is considered a comment.
# This is a single-line comment
print("Hello, World!") # This comment is after code
2. Multi-line Comments
- Python does not have a specific syntax for multi-line comments like some other languages.
- However, you can use multiple
#
symbols for each line or use a multi-line string (enclosed in triple quotes"""
or'''
).
# This is a multi-line comment
# using multiple single-line comments.
# It spans multiple lines.
"""
This is also a multi-line comment
using a multi-line string.
It is not assigned to any variable, so it is ignored.
"""
print("Hello, World!")
Best Practices for Using Comments
- Explain Why, Not What: Comments should explain why something is done, not what is being done (the code itself should be clear enough for that).
- Avoid Over-commenting: Too many comments can make code harder to read. Use comments only when necessary.
- Keep Comments Updated: Ensure comments are updated when the code changes to avoid confusion.
Example
# Calculate the area of a circle
radius = 5
pi = 3.14159
area = pi * radius**2 # Formula: πr²
print("Area of the circle:", area)
In this example:
- The first comment explains the purpose of the code.
- The second comment clarifies the formula being used.