Comments explain intent to people reading source code. They are not instructions executed by the Python interpreter.
Understanding the Concept
A single-line comment begins with # and continues to the end of that physical line. Python does not provide a separate dedicated multiline comment delimiter; write adjacent # lines for a longer explanation. Triple-quoted strings may be used for docstrings or multiline text, but they are not equivalent to comment syntax. Write comments for non-obvious decisions, assumptions, and important constraints. Avoid comments that simply repeat what a clear line already says.
When and Why You Would Use This
A short billing rule illustrates a useful comment. The comment explains why a delivery fee is charged instead of restating the addition syntax.
Practical Example
product_total = 60
# Free delivery is available only when the product total reaches 75.
delivery_fee = 0 if product_total >= 75 else 5
print("Total:", product_total + delivery_fee)
Understanding the Example
The output is Total: 65. The comment documents the rule. Python ignores the comment while still evaluating the conditional expression. More complete lessons will introduce conditional syntax.
Example Output
Total: 65
Try It Yourself
Add a comment to a calculator explaining its conversion factor. Remove a redundant comment that merely describes an addition.
Common Beginner Mistakes
- Using triple-quoted strings as a substitute for comments without understanding that they are string expressions.
- Writing outdated comments that disagree with current behavior.
- Explaining the obvious instead of documenting why a rule exists.
Key Takeaways
- Use # for Python source comments.
- Comments are for intent and assumptions, not program execution.
- Keep comments accurate, concise, and valuable.