Python Basics
Python Comments
Learn how to use comments in Python to document your code and explain complex logic.
Python Comments
Comments can be used to explain Python code. Comments are used to make code more readable. Comments can be used to prevent execution when testing code.
Creating a Comment
A comment starts with a #, and Python will ignore it:
Multiline Comments
Python does not really have a syntax for multiline comments. To add a multiline comment you could insert a # for each line, or use a multiline string (triple-quoted string).
Since Python will ignore string literals that are not assigned to a variable, you can add a multiline string (triple quotes) in your code, and place your comment inside it.
Why Use Comments?
Good comments:
- Explain why code does something (not what)
- Document function parameters and return values
- Mark areas for improvement (TODO comments)
- Temporarily disable code during debugging
Example
python
# Single-line comment
x = 5 # inline comment
# This is a comment
# written in
# more than one line
"""
This is a multiline
docstring / comment
It can span multiple lines
"""
# TODO: Optimize this function
def slow_function(data):
result = []
for item in data:
# Process each item
result.append(item * 2)
return result
# Temporarily disable code:
# old_function() # commented out
# Explain why, not what:
# Multiply by 0.01 to convert from cents to dollars
price_dollars = price_cents * 0.01Try it yourself — PYTHON