Comments can be used to explain Python code, make the code more readable, or prevent execution when testing code.
Concept Explanation
Writing code is mainly for the computer, but comments are entirely for human readers. When the Python interpreter runs your code, it completely ignores anything marked as a comment.
Why use them? As your scripts grow larger, you or other developers will inevitably forget why certain logic was written a specific way. Comments serve as sticky notes attached to your code, explaining the "Why," not just the "What."
Syntax or Core Structure
Creating a Comment
Comments starts with a #, and Python will ignore them:
# This is a comment
print("Hello, World!")
Multi Line Comments
Python does not really have a syntax for multi line comments. To add a multiline comment you could insert a # for each line, or use a triple-quoted string.
"""
This is a multi-line string.
Since it isn't assigned to any variable,
Python reads it and throws it away, acting as a multi-line comment!
"""
Code Example #1 (Basic)
Here is how you might comment a basic math script.
# Calculate the area of a rectangle
length = 5
width = 10
area = length * width
print(area) # Prints the final calculated area
Code Example #2 (Intermediate)
Comments are incredibly useful for temporarily disabling code when you are trying to hunt down a bug. This is known as "commenting out" code.
print("Step 1 Complete")
# print("Step 2 Complete") <- This is currently disabled!
print("Step 3 Complete")
Real World Example
In professional environments, complex algorithms require detailed comments explaining the business rules behind the math.
# -----------------------------------------
# TAX CALCULATION MODULE
# Authored by: Jane Doe
# -----------------------------------------
user_income = 85000
# According to state law article 4B, incomes over $80k are heavily taxed
if user_income > 80000:
# Tax rate is 25% for high earners
tax = user_income * 0.25
else:
# Standard base tax rate is 15%
tax = user_income * 0.15
print(f"Total tax owed: $${tax}")
Common Mistakes
- Stating the Obvious: Writing
x = 5 # Sets x to 5. This is redundant and clutters the file. The code speaks for itself. - Outdated Comments: Updating a piece of code but forgetting to update the comment above it. A wrong comment is actively worse than no comment!
Best Practices
- Explain the "Why", not the "What": Clear variable and function names already show what the code runs. Use comments to document constraints, invariants, workarounds, or external business rules.
- Follow PEP 8 Spacing: Always put one space after
#(# Comment, not#Comment), and put at least two spaces before an inline comment (x = 1 # Offset by header byte). - Use Real Docstrings for APIs: A triple-quoted literal right under
def,class, or at the top of a module becomes its official__doc__attribute, readable byhelp()and IDEs. Outside those positions, prefer#on each line rather than orphan"""..."""strings. - Special Tooling Directives: Python linters, type checkers, and encoding headers also use specially formatted comments that tools parse while Python skips them:
# type: ignore[assignment]— tellsmypyor Pyright to allow an intentional dynamic override.# noqa: E501— tellsrufforflake8why a single long URL/regex line should stay unbroken.# TODO(handle): ...— searchable action marker tied to an owner or issue reference.
def calculate_late_fee(days_overdue: int, daily_rate: float) -> float:
"""Return capped late fee for an overdue invoice in USD."""
if days_overdue <= 0:
return 0.0
# Billing policy v2.4 caps penalties at 30 days to avoid negative balances
billable_days = min(days_overdue, 30)
return round(billable_days * daily_rate, 2)
Practice Exercises
- Add Explanations: Write a script that calculates the number of seconds in a day. Add comments explaining any non-obvious unit conversions or assumptions.
- Comment Out for Debugging: Write three
print()statements. Temporarily disable the middle one with#and verify only two lines run. - Docstring vs Comment: Write a
celsius_to_fahrenheit(temp)function with a proper"""..."""docstring for callers and a#comment inside explaining the9 / 5scaling factor, then inspectcelsius_to_fahrenheit.__doc__.