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.
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.
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:
Comment Best Practices
- Comments should be clear and concise: Avoid writing meaningless comments like
x = 5 # Assign 5 to x. - 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").
- Keep comments updated: When you modify code, synchronize related comments to avoid misleading others.
- Write comments in English: This is the international best practice, facilitating global developer collaboration.
- 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.