Python offers multiple ways to add comments to your code, each serving different purposes:
graph TD
A[Python Comment Types] --> B[Inline Comments]
A --> C[Block Comments]
A --> D[Docstring Comments]
A --> E[TODO Comments]
Inline comments appear on the same line as code:
age = 25 ## User's current age
total_price = quantity * price ## Calculate total price
- Keep them short and concise
- Explain complex logic or non-obvious calculations
- Avoid redundant explanations
Block comments describe larger code sections:
## Customer information processing
## This block handles user registration and validation
def process_customer_registration(name, email):
## Validate email format
if validate_email(email):
## Create new customer record
create_customer(name, email)
Docstrings provide documentation for modules, classes, and functions:
def calculate_area(length, width):
"""
Calculate the area of a rectangle.
Args:
length (float): Length of the rectangle
width (float): Width of the rectangle
Returns:
float: Area of the rectangle
"""
return length * width
TODO comments mark future improvements or pending tasks:
def complex_algorithm():
## TODO: Optimize performance
## TODO: Add error handling
pass
| Comment Type |
Use Case |
Syntax |
Scope |
| Inline |
Quick explanations |
# |
Single line |
| Block |
Describing code blocks |
# |
Multiple lines |
| Docstring |
Function/module documentation |
""" or ''' |
Entire function/module |
| TODO |
Future improvements |
## TODO: |
Specific task |
You can temporarily disable code execution:
## Debugging: temporarily disable this line
## problematic_function()
LabEx Recommendation
When writing comments, focus on clarity and meaningful explanations that help other developers (including your future self) understand the code's purpose and functionality.