Python注释语法详解:单行、多行与避坑指南¶
Comments are the “user manuals” of code, helping both us and others understand the purpose of the code, and making it easier to review later. Python has simple comment syntax, but beginners may confuse single-line and multi-line comment styles. Let’s master them with straightforward syntax!
一、单行注释:最常用的“一句话说明”¶
In Python, single-line comments start with #, and everything after # is automatically ignored by Python and not executed.
Usage Example:
# This is a single-line comment explaining the function of the next line
print("Hello, Python!") # You can also place it on the right side of a code line to explain its function
# Note: Only the content after # is a comment; leading spaces don't affect it
# However, if there's code before #, there must be a space between them, otherwise it will throw an error
Key Points:
- # only affects content on its line and does not impact other lines.
- Do not put # inside a string, e.g., print("# Hello") will output # Hello (where # is treated as part of the string).
二、多行注释:需要“一大段说明”¶
Python does not have multi-line comment syntax like other languages (e.g., Java’s /* */), but we can use three single quotes ''' or three double quotes """ to achieve multi-line comments.
Usage Example:
# Multi-line comment: Use three single quotes without assigning to a variable
'''
This is the first line of a multi-line comment
You can write multiple lines of content here
Explain the purpose of a code block
For example, describe the function of a function
'''
# Similarly, three double quotes work the same way
"""
This is a multi-line comment using double quotes
Line breaks are also treated as part of the comment
"""
Note:
- This type of multi-line comment is essentially a “string.” If written inside a function, it becomes a docstring (document string), which can be viewed with help(). For example:
def greet():
"""
Print a greeting message
"""
print("Hello!")
help(greet) # Calling help() will display the docstring content
As a beginner, just remember: Use three quotes for multi-line comments, do not assign them to variables, and write them directly in the code.
三、注释的“避坑指南”¶
- Do not “hide” code with comments: For example,
# print("This code is commented out")is meaningless because it serves no purpose. Either delete it or keep the real code. - Avoid redundant comments: For example,
# This line printsis unnecessary. Directly reading the code logic is clearer. Comments should explain “why” (not “what”). - Don’t confuse multi-line comments with strings: For example,
my_var = '''This is a comment'''assigns a string tomy_var. Although it doesn’t break the program, this is not the correct use of comments. Comments should use three quotes without variable assignment.
总结¶
Python comments are simple:
- Single-line comments: Use # for explaining single-line code.
- Multi-line comments: Use ''' or """ for long explanations.
Master these two syntaxes to write clear comments that make your code “speak for itself”!