Skip to content

Python Comments

Comments are used in Python to add explanations or notes to the code. They are not executed and do not affect the program’s functionality. Comments are crucial for enhancing code readability and for providing context to readers.

A good comment explains why the code does something, not what it does — the code itself already shows the what.

why_not_what.py
# Bad: restates the obvious
x = x + 1  # add 1 to x
 
# Good: explains the reason
x = x + 1  # advance to the next page; pages are 1-indexed
why_not_what.py
# Bad: restates the obvious
x = x + 1  # add 1 to x
 
# Good: explains the reason
x = x + 1  # advance to the next page; pages are 1-indexed

Diagram:

diagram how Python treats comments mermaid
The interpreter ignores everything after the hash

Single-line Comments

In Python, single-line comments start with the ## symbol. Anything following the ## on that line is considered a comment.

Example:

comment.py
# This is a single-line comment
 
print("Hello, World!")  # This is also a comment after code
comment.py
# This is a single-line comment
 
print("Hello, World!")  # This is also a comment after code

Multi-line Comments

While Python does not have a specific syntax for multi-line comments, you can use triple-quotes ('''''' or """""") to create multi-line string literals. Even though these are technically strings, they are often used as a workaround for creating multi-line comments.

Example:

comment.py
'''
This is a multi-line comment.
It spans multiple lines.
'''
 
"""
Another way to create a multi-line comment.
Use triple-quotes to start and end the comment block.
"""
 
print("Hello, World!")
comment.py
'''
This is a multi-line comment.
It spans multiple lines.
'''
 
"""
Another way to create a multi-line comment.
Use triple-quotes to start and end the comment block.
"""
 
print("Hello, World!")

Comments for Code Documentation

In addition to adding comments for clarifying code, Python has a convention for using docstrings to document functions, modules, and classes. Docstrings are enclosed in triple-quotes and are used to provide information about the code element.

Example:

comment.py
def add_numbers(a, b):
    """
    This function adds two numbers and returns the result.
    
    Parameters:
    - a (int): The first number.
    - b (int): The second number.
    
    Returns:
    int: The sum of a and b.
    """
    return a + b
 
# Usage of the function
result = add_numbers(5, 3)
print("Result:", result)
comment.py
def add_numbers(a, b):
    """
    This function adds two numbers and returns the result.
    
    Parameters:
    - a (int): The first number.
    - b (int): The second number.
    
    Returns:
    int: The sum of a and b.
    """
    return a + b
 
# Usage of the function
result = add_numbers(5, 3)
print("Result:", result)

Accessing a Docstring

Unlike ordinary comments, docstrings are kept by Python at runtime. You can read them with the built-in help()help() function or the __doc____doc__ attribute — this is how editors and help()help() show documentation.

docstring_access.py
print(add_numbers.__doc__)   # prints the docstring text
help(add_numbers)            # prints formatted help
docstring_access.py
print(add_numbers.__doc__)   # prints the docstring text
help(add_numbers)            # prints formatted help

Commenting Out Code

During debugging it is common to temporarily disable a line by turning it into a comment. Most editors do this for a whole selection with Ctrl + /Ctrl + /.

disable.py
print("This runs")
# print("This line is disabled for now")
print("This runs too")
disable.py
print("This runs")
# print("This line is disabled for now")
print("This runs too")

TODO and FIXME Conventions

Teams use tagged comments so tools and editors can find pending work. Common tags include TODOTODO, FIXMEFIXME, and NOTENOTE:

tags.py
# TODO: handle negative numbers
# FIXME: this crashes when the list is empty
# NOTE: prices are stored in cents, not dollars
tags.py
# TODO: handle negative numbers
# FIXME: this crashes when the list is empty
# NOTE: prices are stored in cents, not dollars

The Shebang Line

On Linux and macOS, the first line of an executable script can be a special comment called a shebang. It tells the system which interpreter to use, so the script can be run directly:

script.py
#!/usr/bin/env python3
print("Run me directly with ./script.py")
script.py
#!/usr/bin/env python3
print("Run me directly with ./script.py")

Best Practices for Comments

  1. Be Clear and Concise: Write comments that are easy to understand. Avoid unnecessary comments that restate the obvious.

  2. Keep Comments Updated: If code changes, remember to update the associated comments to ensure accuracy.

  3. Use Docstrings for Documentation: For functions, modules, and classes, utilize docstrings to provide comprehensive documentation.

  4. Avoid Excessive Comments: Code should be self-explanatory whenever possible. Avoid cluttering your code with excessive comments.

Comments play a crucial role in effective communication within your codebase. Use them wisely to make your Python code more understandable and maintainable.

Explore more Python coding practices with our tutorials on Python Central Hub!


Try it: Comments Exercises

Exercise 1 – Single-Line Comment

Exercise 2 – Inline Comment

Exercise 3 – Multi-Line Comment (Docstring)

If this helped you, consider buying me a coffee ☕

Buy me a coffee

Was this page helpful?

Let us know how we did