Comments in Python are used to explain code, make it more readable, and prevent execution of certain lines.
✅ Python ignores comments when executing code.
✅ Useful for documentation and debugging.
1. Single-Line Comments
Single-line comments start with a #
(hash symbol).
Example:
# This is a comment print("Hello, World!") # This prints a message
🔹 Python ignores the comment and only executes the print statement.
2. Multi-Line Comments
Python doesn’t have a built-in multi-line comment feature, but you can use:
Method 1: Using #
on Each Line
# This is a multi-line comment # explaining the next line of code print("Python is awesome!")
Method 2: Using Triple Quotes ("""
or '''
)
Triple quotes can also be used as multi-line comments:
""" This is a multi-line comment. Python will ignore these lines. """ print("Welcome to Python!")
🔹 Note: Triple quotes are actually used for docstrings (documentation for functions and classes).
3. Using Comments for Debugging
You can disable a line of code by turning it into a comment:
x = 10 # y = 20 # This line is disabled print(x) # Output: 10
4. Docstrings (Documentation Strings)
Docstrings are special multi-line comments used for documenting functions, classes, and modules.
def greet(): """This function prints a greeting message.""" print("Hello, Python!") greet()
You can access the docstring using:
print(greet.__doc__)
🔹 Output:
This function prints a greeting message.
5. Best Practices for Writing Comments
✅ Keep comments short and meaningful.
✅ Explain why the code is written, not what it does.
✅ Use comments only when necessary to avoid clutter.
Bad Comment Example:
x = 10 # Assigns 10 to variable x
Good Comment Example:
# Setting initial value for calculation x = 10