Python Comments


What Are Python Comments?

Comments are lines in code that are ignored during execution. They're used to:

  • Explain code:
  • Make it readable:
  • Temporarily disable code:
  • Document functions or logic:

Types of Comments in Python


1. Single-Line Comments

Use the # symbol.

# This is a single-line comment
x = 10  # Assign 10 to x
print(x)

Output:

10

2. Multi-Line Comments

Python doesn't have true multi-line comment syntax like other languages, but you can use:

# This is a comment
# spread over multiple
# lines using hash

Option B: Triple Quotes (for docstrings or non-assigned strings)


"""
This is a multi-line comment.
Technically, it’s a string not assigned to any variable.
"""
print("Hello")

Output:

Hello

Note: Only use triple quotes for documentation or if you're okay with creating a string object.


Best Practices for Writing Comments in Python

Best Practice Description
Be concise Explain "why", not just "what"
Update comments Keep them relevant as the code changes
Use complete sentences Write full sentences for clarity
Avoid obvious comments Don't state the obvious (e.g., x = 5 # Set x to 5)
Use comments to outline logic Help others understand decision-making
Use docstrings for functions/classes Explain purpose, parameters, return values

Example: Well-Commented Code

def factorial(n):
    """
    Calculate factorial of a number.
    
    Parameters:
    n (int): A non-negative integer

    Returns:
    int: Factorial of n
    """
    # Start with result as 1
    result = 1

    # Loop from 1 to n
    for i in range(1, n + 1):
        result *= i  # Multiply current result with i
    
    return result

print(factorial(5))  # Output: 120

Output:

120

Bad Commenting Example

# This function calculates factorial
def factorial(n):
    # Start result at 1
    result = 1
    # Loop from 1 to n+1
    for i in range(1, n + 1):
        result = result * i
    return result

Comments here are redundant and do not add clarity.


Summary of Commenting

  • Use # for quick notes: Add single-line comments using the # symbol.
  • Use docstrings (""") for documentation: Provide detailed explanations for functions, classes, or modules.
  • Focus on the why, not just the how: Explain the reasoning behind complex logic, not just what the code is doing.
  • Keep comments updated: Make sure comments reflect the current state of the code to avoid confusion.
  • Avoid over-commenting or stating the obvious: Only comment on code that truly needs explanation.