Comments in Python are essential for improving code readability, explaining complex logic, and providing information about the purpose or functionality of code blocks.
Comments are not executed by the Python interpreter and are meant to serve as notes for anyone reading the code, including future developers or even your future self.
In this tutorial, you'll learn:
What are comments in Python?
Single-line comments
Multi-line comments
Commenting code for documentation
Practical examples of using comments in Python code
1. What Are Comments in Python?
Comments are lines in a Python script that the interpreter ignores. They are typically used to explain what the code does, why certain decisions were made, or to provide additional context that might not be obvious from the code itself.
In Python, comments start with a # symbol and continue until the end of the line.
2. Single-Line Comments
The simplest form of a comment in Python is a single-line comment. Single-line comments are placed on the same line as the code or on their own line and begin with a #.
Example 1: Single-Line Comments
# This is a comment explaining that the following code prints a message print("Hello, World!") # This prints a greeting message
Output:
Hello, World!
In this example:
The first line is a comment that explains what the next line of code does.
The comment # This prints a greeting message is placed at the end of the line where the print() function is used.
3. Multi-Line Comments
Python does not have a native syntax for multi-line comments like some other languages (e.g., /* */ in C/C++ or Java). However, you can achieve multi-line comments in two common ways:
Using multiple # symbols.
Using multi-line string literals (which are typically used for documentation).
Example 2: Multi-Line Comments with #
# This is a multi-line comment # It spans multiple lines # Each line starts with a # symbol print("Multi-line comment example")
Output:
Multi-line comment example
Example 3: Multi-Line Comments with String Literals
Multi-line string literals (enclosed in triple quotes) can be used as comments. These string literals are ignored if they are not assigned to any variable or used in a function.
""" This is a multi-line comment using triple quotes. The interpreter ignores this unless used in a function or assigned to a variable. """ print("Using a multi-line string as a comment")
Output:
Using a multi-line string as a comment
However, using triple quotes for comments is not considered a best practice because this syntax is intended for docstrings (used for documenting functions, classes, and modules).
4. Commenting Code for Documentation
While comments are important, Python also has a built-in feature for documenting code called docstrings. Docstrings are used to describe the purpose and functionality of functions, classes, and modules. These comments are written inside triple quotes (“”” “””) and can span multiple lines.
Example 4: Docstrings for Functions
def greet(name): """ This function greets the person whose name is passed as an argument. Parameters: name (str): The name of the person to greet. Returns: None """ print(f"Hello, {name}!") # Calling the function greet("Alice")
Output:
Hello, Alice!
In this example:
The docstring explains what the greet() function does, what parameters it expects, and what it returns.
Docstrings are typically placed right after the function, class, or module definition.
You can access the docstring of a function using the help() function or by calling __doc__:
print(greet.__doc__)
Output:
This function greets the person whose name is passed as an argument. Parameters: name (str): The name of the person to greet. Returns: None
5. Practical Examples of Using Comments in Python Code
Example 5: Using Comments to Explain Complex Logic
When dealing with complex algorithms, it is helpful to add comments that explain how the logic works.
def factorial(n): # This function calculates the factorial of a number # Factorial is the product of all positive integers less than or equal to n if n == 0 or n == 1: return 1 else: return n * factorial(n - 1) print(factorial(5)) #
Output:
120
In this example, the comment explains what the factorial() function does and how the recursive algorithm works.
Example 6: Commenting Out Code for Debugging
When debugging or testing different parts of a program, you can temporarily disable certain lines of code by commenting them out.
def add(a, b): return a + b def subtract(a, b): return a - b # Uncomment the following line to test the add function # print(add(10, 5)) # Test the subtract function print(subtract(10, 5)) #
Output:
5
In this example, the add(10, 5) line is commented out for testing purposes. You can easily re-enable it by removing the # symbol.
Example 7: Adding TODO Comments
You can use comments to mark parts of your code that need further work or improvements. These are often labeled as TODO comments.
def calculate_area(radius): # TODO: Add input validation for radius return 3.14 * radius * radius # Calling the function print(calculate_area(5))
Output:
78.5
In this case, the TODO comment serves as a reminder that input validation needs to be added later.
Example 8: Commenting for Future Reference
Comments can also provide important information for future reference, such as optimization suggestions or reasons for specific design decisions.
def process_data(data): # Using a simple for loop here instead of list comprehension # because the dataset might be large, and list comprehension can consume more memory result = [] for item in data: result.append(item * 2) return result print(process_data([1, 2, 3])) #
Output:
[2, 4, 6]
Output:
[2, 4, 6]
Here, the comment explains why a for loop is used instead of list comprehension due to concerns about memory usage for large datasets.
6. Best Practices for Writing Comments
Keep comments relevant: Ensure that your comments accurately reflect what the code does. Avoid outdated comments that no longer apply after code changes.
Be concise and clear: Comments should be easy to read and understand. Avoid writing long paragraphs—keep it short and to the point.
Avoid obvious comments: Do not comment on trivial things that are self-explanatory.
# Bad comment x = 10 # Set x to 10 # Good comment x = 10 # Initial count of items in the inventory
Use comments to explain “why”, not just “what”: The code itself often shows what is happening, but comments should provide the reasoning behind why something is done.
# The loop breaks if the condition is met to prevent an infinite loop if condition_met: break
Use docstrings for functions, classes, and modules: Always use docstrings to document functions, classes, and modules. This makes your code easier to maintain and helps other developers (or your future self) understand the purpose and usage of your code.
Conclusion
Comments are a crucial part of writing readable and maintainable code. They help explain the purpose and logic of the code, making it easier to understand for others (or even yourself, after some time).
Here’s a summary of what you’ve learned:
Single-line comments start with # and are used for brief explanations.
Multi-line comments can be created by using multiple # symbols or string literals (“”” “””), though the latter is better suited for docstrings.
Docstrings are used for documenting functions, classes, and modules and can be accessed programmatically.
Comments can also be used for debugging, marking TODO items, and explaining complex logic or future improvements.