Skip to content

Python Comments

Comments are part of code used for explanation and description. Good comments are key to writing readable, maintainable, and well-documented code. They help other developers (and your future self) quickly understand the code's intent and logic.

Python mainly has two types of comments: single-line comments and multi-line comments.

Single-line Comments

Single-line comments start with the hash symbol #. Everything from # to the end of the line is treated as a comment.

python
# This is a complete single-line comment
name = "Alice"  # This is an inline comment explaining this variable's purpose
# The code below will print a welcome message
print("Hello, " + name)

Usage:

  • Provide brief explanations for single-line code.
  • Add summary comments before code blocks to describe their purpose.
  • Temporarily disable a line of code for debugging by commenting it out.

Multi-line Comments

Strictly speaking, Python doesn't have dedicated multi-line comment syntax like other languages (such as C++'s /* ... */). However, you can use multi-line strings (three single quotes ''' or three double quotes """) to achieve the same effect.

python
'''
This is a multi-line comment,
it can span multiple lines.
'''
def add(a, b):
    """
    This is also a multi-line comment, but when it appears at the beginning of a function, class, or module definition,
    it has a special name: docstring (document string).
    """
    return a + b

print("This code will be executed.")

Docstrings (Document Strings)

As mentioned in the example above, when a multi-line string is the first statement inside a function, method, or class definition, it becomes that object's __doc__ attribute, i.e., a document string.

Docstrings are Python's important feature. Many tools (such as help() function, IDEs, documentation generators) can extract and use them to automatically generate documentation.

A good docstring example:

python
def calculate_area(radius):
    """Calculate the area of a circle.
    
    Args:
        radius (int or float): The radius of the circle.
    
    Returns:
        float: The calculated area of the circle.
    """
    pi = 3.14159
    return pi * (radius ** 2)

# You can view the document string via help() function
# or directly access __doc__ property
print(calculate_area.__doc__)

Comment Best Practices

  1. Comments should be clear and concise: Avoid writing meaningless comments like x = 5 # Assign 5 to x.
  2. Comments should explain "why" not "what": Good code should be self-explanatory. Comments should explain complex logic or design decisions ("why"), not repeat the code ("what").
  3. Keep comments updated: When you modify code, synchronize related comments to avoid misleading others.
  4. Write comments in English: This is the international best practice, facilitating global developer collaboration.
  5. Follow PEP 8 Style Guide for Comments: PEP 8 provides guidelines for Python comment formatting, for example, inline comment # should be followed by two spaces.

Content is for learning and research only.