Comments

Comments are messages you write for yourself and other programmers. Python ignores them completely – they exist purely to explain your code. Good comments make code easier to understand, maintain, and debug.

Single-Line Comments

Start a comment with the # symbol. Everything after it on that line is ignored:

# Calculate the total price including tax
subtotal = 100
tax_rate = 0.08    # 8% sales tax
total = subtotal * (1 + tax_rate)

Comments can appear on their own line or at the end of a code line.

Multi-Line Comments

For longer explanations, use multiple # lines:

# This function calculates shipping costs based on weight.
# Rates are:
#   - Under 1 lb: $5
#   - 1-5 lbs: $10
#   - Over 5 lbs: $15

Python also has triple-quoted strings that span multiple lines. While technically strings, they're often used as comments:

"""
This program converts temperatures between
Celsius and Fahrenheit. It prompts the user
for input and displays the converted value.
"""

What Makes a Good Comment?

Explain why, not what. Code shows what happens; comments should explain reasoning:

# Good: explains why
tax_rate = 0.08    # California state tax rate

# Bad: just restates the code
tax_rate = 0.08    # Set tax rate to 0.08

Clarify complex logic:

# Use modulo to check if year is a leap year
# Leap years are divisible by 4, except century years
# unless also divisible by 400
if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0):

Note non-obvious decisions:

# Using integer division to round down to nearest dollar
# (customer preference over standard rounding)
discount = total_cents // 100

When Not to Comment

Avoid redundant comments that add no information:

# Don't do this:
x = x + 1    # Add 1 to x
name = "Alice"    # Set name to Alice

If your code needs extensive comments to be understood, consider whether clearer variable names or simpler structure would help more.

Comments for Future You

The most important reader of your comments is often yourself, weeks or months later. Write comments that answer questions you might have when returning to the code:

  • Why did I choose this approach?
  • What edge cases does this handle?
  • What would break if I changed this?

See More

Further Reading

You need to be signed in to leave a comment and join the discussion