目次
1. Basics of Python Commenting and Its Importance
Python commenting is an essential tool for making code easier to understand when others—or you—look at it later. Leaving explanations and notes in the code improves maintainability, makes it smoother to pinpoint error causes and explain logic. It also comes in handy for temporarily disabling code during development testing.1.1 Basics of Single-Line Commenting
Python single-line comments use “#”. Placing “#” at the start of a line treats the entire line as a comment.# This is a comment
print("Hello, World!") # This part is also treated as a comment
As shown, you can add comments that explain the code and help with future modifications.
1.2 Overview of Multi-Line Comments
A common way to comment out multiple lines is to add “#” to each line individually. This requires manually inserting “#” on each line, but it’s very effective for disabling long code blocks.# This is the comment on line 1
# This is the comment on line 2
# This is the comment on line 3
There are also several efficient methods to reduce the hassle of multi-line commenting, which will be discussed later.
2. Two Ways to Do Multi‑Line Commenting in Python
There are several handy techniques for multi‑line commenting. Below are two of the most common methods.2.1 Multi‑Line Commenting Using “#”
Commenting multiple lines with “#” is the simplest and most common approach.# This is the comment on line 1
# This is the comment on line 2
# This is the comment on line 3
However, it becomes tedious for many lines, so this method is best suited for relatively small blocks.2.2 Multi‑Line Comments Using Triple Quotes
In Python, you can comment out multiple lines by using three consecutive single quotes (”’ ) or double quotes (“”” ). This is originally meant for documentation strings (docstrings), but it can also serve as a commenting alternative."""
This is a multi-line comment
You can comment out multiple lines
"""
However, because this method is recognized as a string, it isn’t technically a comment. It can consume unnecessary resources, so caution is advised especially in large projects or situations where memory usage is critical.</final3. Common Errors and Workarounds When Commenting Out Python Code
There are several points to watch out for when commenting out code. In particular, you need to be careful about indentation errors and the use of triple quotes.3.1 Avoiding Indentation Errors
Python enforces strict indentation rules, and an IndentationError occurs if the code is not properly indented. Even when using triple-quoted comments, misaligned indentation can cause unexpected errors.def example():
"""
This is a comment
"""
print("Hello, World!") # This will cause an indentation error
Keeping indentation consistent is extremely important in Python.