Skip to main content

Python Comments

Python Comments

Comments play a crucial role in writing clean, maintainable, and understandable Python code. They help developers document their code, making it easier for others (and themselves) to read and modify later. This article explores everything you need to know about Python comments, including:

  • Types of Comments (Single-line, Multi-line, Docstrings)
  • Writing Clean Comments (When & How to Comment Effectively)
  • Examples & Common Use Cases

1. What Are Python Comments?

Comments are non-executable lines in Python code used to describe its functionality. They are ignored by the Python interpreter but help improve code readability and maintainability.

Why Use Comments?

  • Improve code readability
  • Explain complex logic
  • Temporarily disable code (for debugging)
  • Generate documentation (using docstrings)

2. Types of Python Comments

A. Single-Line Comments

Single-line comments in Python start with #. They are typically used for short explanations.

Example

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

B. Multi-Line Comments

Python does not have a dedicated multi-line comment syntax. However, you can use:

01. Multiple # lines:

Example

# This is a multi-line comment
# spanning multiple lines
print("Hello")

02. Triple-quoted strings: Though not actual comments, they can serve the same purpose.

Example

"""
This is a multi-line string
often used as a pseudo-comment.
"""
print("Hello")

Note: This is a string literal, but if not assigned to a variable, Python ignores it.

C. Docstrings (Documentation Strings)

Docstrings are special comments used to document functions, classes, and modules. They are enclosed in triple quotes and can be accessed via help().

Example

def add(a, b):
    """
    Adds two numbers and returns the result.
    
    Args:
        a (int): First number
        b (int): Second number
    
    Returns:
        int: Sum of a and b
    """
    return a + b

print(add.__doc__)  # Prints the docstring

Output:

    Adds two numbers and returns the result.
    
    Args:
        a (int): First number
        b (int): Second number
    
    Returns:
        int: Sum of a and b

3. Clean Comments

✅ Do’s:

  • Explain "why," not "what"

Example

# Bad:
x = x + 1  # Increments x by 1

# Good:
x = x + 1  # Adjusts for zero-based indexing
  • Use docstrings for functions & classes
  • Keep comments short and relevant
  • Update comments when code changes

❌ Don’ts:

  • Don’t state the obvious

Example

# Bad:
print("Hello")  # Prints "Hello"
  • Avoid excessive comments (write clear code instead)
  • Don’t use triple quotes for non-docstring comments

4. Common Use Cases

A. Debugging (Temporarily Disable Code)

Comments are useful for debugging by temporarily disabling certain lines of code.

Example

# print("This won't run")
print("This will run")

B. Explaining Complex Logic

Comments help in understanding complex logic, such as checking for prime numbers.

Example

# Check if a number is prime
def is_prime(n):
    if n <= 1:
        return False
    for i in range(2, int(n**0.5) + 1):
        if n % i == 0:
            return False
    return True

C. TODOs & Notes for Developers

Comments can be used to mark sections of code that require future improvements.

Example

# TODO: Optimize this function later
def slow_function():
    pass

5. Conclusion

Use # for single-line comments to explain complex logic or mark TODOs. For detailed documentation, use multi-line docstrings (""") for functions, classes, and modules - these become official documentation accessible via help().

Follow the golden rule: comment the "why" behind code, not the "what", and keep explanations concise. Well-commented code strikes a balance between clarity and brevity, making maintenance easier while avoiding redundant explanations of obvious functionality. Remember to update comments whenever modifying related code to prevent outdated documentation.



Comments