Single-Line Comments
The # character tells Python to ignore everything after it on that line. Use it to explain what your code does.
# Display a welcome message
print("Welcome to Python!")
Try it Yourself โ
End-of-Line Comments
You can also place comments at the end of a line of code. Just make sure the code comes first.
x = 42 # The answer to everything
Try it Yourself โ
Commenting Variables
Use comments to describe what a variable represents when the name alone isn't enough.
pi = 3.14159 # Approximate value of pi
radius = 5 # Circle radius in meters
Try it Yourself โ
Disabling Code
Comments are great for temporarily disabling code during debugging. Just add a # at the start of the line.
# print("This won't run")
print("This will run")
Try it Yourself โ
Multi-Line Comments
Python doesn't have a dedicated multi-line comment syntax. Instead, you can use multiple # lines or a multi-line string that isn't assigned to anything.
"""
This is a multi-line string
used as a comment.
It can span several lines.
"""
print("Still works!")
Try it Yourself โ
Docstrings
Docstrings are multi-line strings that document functions, classes, and modules. They're technically not comments, but they serve the same purpose.
def greet(name):
"""Say hello to someone."""
print(f"Hello, {name}!")
greet("Alice")
Try it Yourself โ
Good Comments vs Bad Comments
Good comments explain why, not what. The code already says what it does. Use comments to explain decisions, calculations, or tricky parts.
# Bad comment - explains the obvious
x = x + 1 # Add one to x
# Good comment - explains the reasoning
x = x + 1 # Offset for zero-based index
Try it Yourself โ
Inline Comments
Avoid long inline comments that break the flow. If you need more than a few words, put the comment on its own line above the code.
# Calculate total price with 8% sales tax
total = price * 1.08
Try it Yourself โ
Commenting Out During Debugging
When you're testing different approaches, comment out the old code rather than deleting it. Once you're sure the new code works, clean up the comments.
# print("Version 1")
print("Version 2 - improved")
Try it Yourself โ