If you want to write your code just to explain a block of code or to avoid the execution of a specific part of code while testing, then python comments comes in handy.
Single-line comment
To write a single-line comment just add a # at the start of the line.
# This is a single-line comment
print("Hello World!")The line starting with # is ignored by the Python interpreter. It's only there for understanding.
Multi-Line Comment
In Python, there are two ways to write multi-line comments:
- Using
#on each line:
You can write comments over multiple lines by starting each line with the # symbol.
# This is a comment
# that spans multiple
# lines
print("Hello, World!")2. Using a multi-line string (triple quotes):
While multi-line strings (triple quotes: """ or ''') are typically used for docstrings (documentation strings), they can also be used to create multi-line comments, as Python will ignore them if they’re not assigned to a variable or used in any other way.
"""
This is a multi-line comment
using a string.
Python will ignore this string.
"""
print("Hello, World!")Best Practices for Comments
- Use comments to explain "why" rather than "what":
Use comments to explain the reasoning behind your code, especially for more complex sections.
# Using a while loop because we need to repeat the task until the condition is met
while counter < 10:
counter += 1- Avoid over-commenting:
Don't add comments for every single line of code. Your code itself should be as readable as possible.
# Bad practice
counter = 10 # Set counter to 10
result = counter * 2 # Multiply counter by 2Instead, just write clear code:
counter = 10
result = counter * 2 # This line is already clear👉 Next tutorial: Python Print Function