CodeSparks Logo

CodeSparks

PYTHON

08
CHAPTER
ACTIVE

Comments in Python

Comments are essential for writing maintainable, readable code. They allow you to explain your logic, document functions, and leave notes for yourself and other developers. Good commenting habits distinguish professional programmers from beginners.

What are Comments?

DEFINITION
Comment
Text in your code that is ignored by the Python interpreter but provides information to humans reading the code. Comments explain what code does, why it works that way, or provide other useful information.

Comments are completely ignored when your program runs - they exist solely for human readers. Python offers several ways to add comments, each suited for different purposes and situations.

Single-line Comments

Single-line comments begin with the hash symbol (#) and continue to the end of the line. They're perfect for brief explanations and inline documentation.

PYTHON
# This is a single-line comment
print("Hello, World!")

# Comments can explain what code does
name = "Alice"  # Store the user's name
age = 25       # Store the user's age

# Comments can be on their own lines
# or at the end of code lines
result = 10 + 5  # Calculate the sum

# Multiple single-line comments
# can be used to create
# longer explanations

# TODO: Add error handling here
# FIXME: This calculation might be wrong
# NOTE: Consider optimizing this section

print(name)  # Output the name variable

Multi-line Comments

Python doesn't have a specific multi-line comment syntax like some languages, but you can use triple quotes to create multi-line strings that aren't assigned to variables, effectively creating multi-line comments.

PYTHON
"""
This is a multi-line comment using triple double quotes.
It can span multiple lines and is useful for longer explanations,
license information, or detailed documentation.
"""

'''
You can also use triple single quotes
for multi-line comments. The effect is the same.
This is often used for temporarily commenting out
large blocks of code during development.
'''

def calculate_area(length, width):
    """
    This is actually a docstring, not just a comment.
    It documents what this function does.
    """
    return length * width

# Sometimes developers use multiple # symbols
#####################################
# IMPORTANT SECTION STARTS HERE    #
#####################################

# Block comment explaining complex logic
# Step 1: Get user input
# Step 2: Validate the input
# Step 3: Process the data
# Step 4: Return the result

Docstrings

DEFINITION
Docstring
A special type of comment that appears as the first statement in a module, function, class, or method definition. Docstrings are accessible at runtime and are used by documentation tools.

Docstrings are Python's official way to document code. Unlike regular comments, docstrings can be accessed programmatically and are used by tools like help() and documentation generators.

PYTHON
def greet_user(name, greeting="Hello"):
    """
    Greet a user with a personalized message.
    
    Args:
        name (str): The name of the user to greet
        greeting (str): The greeting to use (default: "Hello")
    
    Returns:
        str: A formatted greeting message
    
    Examples:
        >>> greet_user("Alice")
        'Hello, Alice!'
        >>> greet_user("Bob", "Hi")
        'Hi, Bob!'
    """
    return f"{greeting}, {name}!"

class Calculator:
    """
    A simple calculator class for basic arithmetic operations.
    
    This class provides methods for addition, subtraction,
    multiplication, and division operations.
    """
    
    def add(self, a, b):
        """Add two numbers and return the result."""
        return a + b
    
    def divide(self, a, b):
        """
        Divide two numbers and return the result.
        
        Args:
            a (float): The dividend
            b (float): The divisor
            
        Returns:
            float: The quotient
            
        Raises:
            ValueError: If b is zero
        """
        if b == 0:
            raise ValueError("Cannot divide by zero")
        return a / b

# Accessing docstrings programmatically
print(greet_user.__doc__)
help(greet_user)
FUN FACT

The built-in help() function in Python displays docstrings! Try typing help(print) or help(len) in the Python interpreter to see how professional documentation looks.

Best Practices

Good commenting is an art that balances being helpful without cluttering your code. Here are essential guidelines for effective commenting.

  • Explain WHY, not WHAT: Focus on the reasoning behind code rather than describing what it obviously does
  • Keep comments current: Update comments when you change code to avoid misleading information
  • Write for your future self: Comments should help you understand code months later
  • Use docstrings for functions: Document parameters, return values, and behavior
  • Comment complex logic: Explain tricky algorithms or business rules
  • Use TODO and FIXME: Mark areas that need attention or improvement
PYTHON
# GOOD COMMENTS - Explain WHY and provide context

def calculate_tax(income, tax_rate):
    """
    Calculate income tax using progressive tax brackets.
    
    Uses the standard deduction and applies tax rate only
    to income above the threshold to avoid double taxation.
    """
    # Standard deduction for 2024 tax year
    standard_deduction = 12950
    
    # Only tax income above the standard deduction
    taxable_income = max(0, income - standard_deduction)
    
    return taxable_income * tax_rate

# BAD COMMENTS - State the obvious

def calculate_tax(income, tax_rate):
    # Calculate tax
    standard_deduction = 12950  # Set standard deduction to 12950
    taxable_income = max(0, income - standard_deduction)  # Subtract deduction
    return taxable_income * tax_rate  # Multiply by tax rate

# GOOD - Explain complex business logic
def process_discount(price, customer_type, purchase_amount):
    # VIP customers get 15% discount on orders over $100
    # Regular customers get 10% discount on orders over $150
    # First-time customers get 5% discount on any order
    
    if customer_type == "vip" and purchase_amount > 100:
        return price * 0.85
    elif customer_type == "regular" and purchase_amount > 150:
        return price * 0.90
    elif customer_type == "first_time":
        return price * 0.95
    else:
        return price

# GOOD - Document assumptions and limitations
def fibonacci(n):
    """
    Calculate the nth Fibonacci number using recursion.
    
    WARNING: This implementation is inefficient for large n
    due to repeated calculations. Consider using memoization
    or iteration for n > 30.
    
    Args:
        n (int): Position in Fibonacci sequence (must be >= 0)
    
    Returns:
        int: The nth Fibonacci number
    """
    if n < 0:
        raise ValueError("n must be non-negative")
    if n <= 1:
        return n
    return fibonacci(n-1) + fibonacci(n-2)

# GOOD - Mark areas for improvement
def user_registration(username, password):
    # TODO: Add password strength validation
    # FIXME: Username should be case-insensitive
    # NOTE: Consider adding email validation
    
    if len(password) < 8:
        return False, "Password too short"
    
    # Temporary simple validation - improve later
    if username.lower() in ["admin", "root", "test"]:
        return False, "Username not allowed"
    
    return True, "Registration successful"

Effective commenting is a crucial programming skill. Comments should make your code more accessible to others and to your future self. Remember: good code is self-documenting, but even the best code benefits from thoughtful comments that explain context, assumptions, and complex logic.