Python Comments
Learn to document your code effectively with comments and docstrings
💬 Understanding Comments
Comments are essential for writing maintainable code. They explain what your code does, why it does it, and how it works. Good comments make your code readable for others and for your future self!
# This is a comment
print("Hello, World!") # This is also a comment
Types of Comments
Single Line Comments
Use # for single line comments and inline explanations
# This is a single line comment
print("Hello") # Inline comment
Multi-line Comments
Use triple quotes for longer explanations
"""
This is a multi-line comment
that spans several lines
"""
Docstrings
Document functions, classes, and modules
def greet(name):
"""Return a greeting message."""
return f"Hello, {name}!"
Special Comments
TODO, FIXME, and other markers
# TODO: Add error handling
# FIXME: Memory leak here
🔹 Single Line Comments
Single line comments in Python start with the hash symbol (#)
# This is a single line comment
print("Hello, World!")
# Calculate the area of a rectangle
length = 10 # Length in meters
width = 5 # Width in meters
area = length * width # Area calculation
🔹 Multi-line Comments
Python doesn't have specific multi-line comment syntax, but there are several approaches
# Method 1: Multiple single-line comments
# This is a multi-line comment
# that spans several lines
# Each line starts with a hash symbol
# Method 2: Triple quotes
"""
This is a multi-line comment
using triple double quotes.
It can span multiple lines.
"""
🔹 Docstrings
Docstrings are special comments that document functions, classes, and modules
They use triple quotes and are accessible at runtime through the __doc__ attribute.
def calculate_bmi(weight, height):
"""
Calculate Body Mass Index (BMI).
Args:
weight (float): Weight in kilograms
height (float): Height in meters
Returns:
float: BMI value rounded to 2 decimal places
"""
bmi = weight / (height ** 2)
return round(bmi, 2)
Note: Docstrings are accessible via function_name.__doc__
⚠️ Common Comment Mistakes
# Don't state the obvious
x = 5 # Set x to 5 (BAD)
# Don't use comments for bad code
# This is a hack, but it works (BAD)
messy_code_that_should_be_refactored()
# Don't leave outdated comments
# This function returns a string (but it returns int now)
def get_user_age():
return 25
🔹 Comment Best Practices
Follow these guidelines for effective commenting
✅ Good Practices
# Explain WHY, not WHAT
# Using binary search for O(log n) performance
def binary_search(arr, target):
pass
# Document assumptions
# Assumes input is already validated
def process_data(data):
pass
# Use TODO for future improvements
# TODO: Add caching for better performance
❌ Avoid These
# Don't state the obvious
x = 5 # Set x to 5
# Don't comment bad code
# This is messy but works
terrible_function()
# Don't leave outdated comments
# Returns string (actually returns int)
def get_age():
return 25
🔹 Comment Types
- Explanatory: Explain complex logic
- Warning: Alert about potential issues
- TODO: Mark areas needing work
- Documentation: Describe function/class purpose
🔹 Real-World Example
Here's a well-commented function demonstrating best practices
def validate_password(password):
"""
Validate password strength based on security requirements.
Args:
password (str): The password to validate
Returns:
tuple: (is_valid: bool, errors: list)
"""
errors = []
# Check minimum length requirement
if len(password) < 8:
errors.append("Password must be at least 8 characters")
# Check for uppercase letter using regex
if not re.search(r'[A-Z]', password):
errors.append("Must contain uppercase letter")
# Password is valid if no errors found
is_valid = len(errors) == 0
return is_valid, errors
🔹 Practice Example
# Calculate tip based on service quality
def calculate_tip(bill_amount, service_quality):
"""Calculate tip amount based on service quality."""
# Determine tip percentage based on service
if service_quality == "excellent":
tip_percentage = 0.20 # 20% for excellent
elif service_quality == "good":
tip_percentage = 0.15 # 15% for good
else:
tip_percentage = 0.10 # 10% default
return bill_amount * tip_percentage