How to Comment in Python: Simple Syntax and Examples
In Python, you write a single-line comment by starting the line with
#. For multi-line comments, use triple quotes ''' or """ to enclose the comment block.Syntax
Python supports two main ways to write comments:
- Single-line comment: Start the line with
#. Everything after#on that line is ignored by Python. - Multi-line comment: Use triple single quotes
'''or triple double quotes"""to enclose a block of text. This is often used for longer comments or documentation.
python
# This is a single-line comment ''' This is a multi-line comment. It can span multiple lines. '''
Example
This example shows both single-line and multi-line comments in a Python program. Comments do not affect the program's output.
python
# This function adds two numbers def add(a, b): ''' This function takes two numbers and returns their sum. ''' return a + b result = add(3, 5) print(result) # Output the result
Output
8
Common Pitfalls
Some common mistakes when commenting in Python include:
- Forgetting the
#for single-line comments, which causes Python to treat the text as code and raise errors. - Using triple quotes for multi-line comments but placing them where Python expects code, which can create unintended string literals.
- Using comments to explain obvious code, which can clutter the code instead of helping.
python
# Wrong: missing # causes error # print("Hello") # Correct way # Wrong: triple quotes used as comment but assigned or misplaced text = '''This is a string, not a comment''' # Right: use triple quotes only for actual multi-line comments or docstrings
Quick Reference
| Comment Type | Syntax | Use Case |
|---|---|---|
| Single-line comment | # comment text | Brief notes or explanations on one line |
| Multi-line comment | ''' comment text ''' or """ comment text """ | Longer explanations or documentation blocks |
Key Takeaways
Use # to write single-line comments in Python.
Use triple quotes ''' or """ for multi-line comments or docstrings.
Comments help explain code but should not state the obvious.
Incorrect comment syntax can cause errors or unintended behavior.
Multi-line comments are often used for function or module documentation.