Comments - Adding Notes to Your Code

Welcome to your first lesson about Python comments! Think of comments as sticky notes you put on your code - they help you remember what your code does and help others understand it too.

In this lesson, you'll learn:

1. Single-Line Comments with #

Single-line comments start with the # symbol (called a "hash" or "pound" sign). Everything after the # on that line is completely ignored by Python - it's like the computer can't even see it!

You can use single-line comments in three ways:

# This is a comment on its own line
print("Hello, World!")  # This comment explains what this line does

You can write anything in comments - Python completely ignores them:

# You can write anything here - Python ignores it completely
# Even if you write nonsense: aksjdlakjsd 12345 !@#$%

print("Second line")
# print("This line won't run because it's commented out")

Notice how Python completely skips over the commented lines! The interpreter acts like they don't exist at all.

Exercise: Your First Comments

Add a single-line comment above the print statement that says "Display a greeting message".

# TODO: Add a comment here that says "Display a greeting message" print("Welcome to Python!")

2. Multi-Line Comments with Triple Quotes

For longer explanations, you can use triple quotes: """ or '''. These create what are technically called "multi-line strings," but when they're not assigned to a variable, they work like comments.

Important difference: Unlike single-line comments with #, Python actually does read and evaluate these triple-quoted strings - but since they're not stored in a variable, they just disappear after being evaluated!

"""
This is a multi-line comment.
You can write as much as you want here.
Python will read this text, but since it's not
assigned to a variable, it just disappears.
"""

print("Hello from Python!")

You can also use single quotes for multi-line comments:

'''
You can also use single quotes for multi-line comments.
This is useful when your comment contains double quotes like "hello".
This text is also evaluated by Python but then discarded.
'''

print("Comments help make code readable!")

See how Python steps through the multi-line comments? It evaluates them as strings, but since they're not saved anywhere, they have no effect on your program.

Exercise: Multi-Line Comment

Add a multi-line comment at the top that explains what this small program does. Include at least two lines in your comment.

# TODO: Add a multi-line comment here that explains what this program does # Include at least two lines in your comment print("Python") print("Programming")

3. The Key Difference: Ignored vs. Evaluated

This is a crucial concept to understand:

Let's see this difference in action by looking at what happens with syntax errors:

# This is completely ignored by Python
# Even syntax errors here won't cause problems: print(hello world
# Python never even looks at this line

print("First line works fine!")

Multi-line comments are evaluated as strings, so they must have valid syntax:

"""
This multi-line comment is evaluated by Python,
so it must be valid Python syntax.
But since it's just a string with no assignment,
it gets discarded after evaluation.
"""

print("Second line also works!")

# Uncomment the next line to see what happens with a syntax error:
# """
# This would cause an error: print(hello world
# """

If you uncommented those last lines, you'd get a syntax error because Python tries to evaluate the multi-line string and finds invalid syntax inside it.

Exercise: Understanding the Difference

Add both types of comments to explain what the code does. Use a single-line comment to explain the calculation and a multi-line comment to describe the overall purpose.

# TODO: Add a multi-line comment explaining the overall purpose of this program side_length = 5 # TODO: Add a single-line comment explaining the calculation below area = side_length * side_length print(area)

4. When and Why to Use Comments

Good programmers use comments to:

"""
Temperature Converter
This program converts Celsius to Fahrenheit
Author: Python Student
Date: Today
"""

# TODO: Add support for Fahrenheit to Celsius conversion
# TODO: Add input validation

celsius = 25  # Room temperature

# Convert using the standard formula: F = (C × 9/5) + 32
fahrenheit = (celsius * 9/5) + 32

print("Temperature in Celsius:", celsius)
print("Temperature in Fahrenheit:", fahrenheit)

# Alternative formula (gives same result):
# fahrenheit = celsius * 1.8 + 32

Exercise: Commenting Best Practices

Add appropriate comments to this code. Include a multi-line comment at the top describing what the program does, and single-line comments explaining the key calculations.

# TODO: Add a multi-line comment describing what this program does hours = 40 rate = 15 # TODO: Add a comment explaining the calculation total_pay = hours * rate print("Hours worked:", hours) print("Hourly rate: $", rate) print("Total pay: $", total_pay)

5. Common Comment Mistakes to Avoid

Here are some common mistakes beginners make with comments:

# BAD EXAMPLES - Don't do this:

x = 5  # Set x to 5 (obvious and unnecessary)
y = 10  # Set y to 10 (obvious and unnecessary)

# This calculates the area
area = x * y  # But this comment is wrong - this calculates area of rectangle!

print("Area:", area)

Here's how to improve those comments:

# GOOD EXAMPLES - Do this instead:

width = 5
height = 10

# Calculate area of rectangle
area = width * height

print("Area:", area)

Exercise: Fix the Comments

The code below has some comment problems. Fix the comments to be more helpful and accurate. Remove unnecessary comments and add useful ones where needed.

# TODO: Fix the comments below to be more helpful quiz_score = 78 # Set quiz_score to 78 exam_score = 92 # Set exam_score to 92 # This adds the scores together and divides by 2 final_score = (quiz_score + exam_score) / 2 # Do math print("Final score:", final_score) # Print the result

🎯 Bring It All Together: A Well-Commented Program

Let's see a complete example that demonstrates good commenting practices with both single-line and multi-line comments.

"""
Simple Shopping Cart Calculator
This program calculates the total cost of items in a shopping cart,
including tax calculation and discount application.

Author: Python Student
Purpose: Demonstrate good commenting practices
"""

# Shopping cart items with prices
item1_price = 29.99  # T-shirt
item2_price = 45.50  # Jeans
item3_price = 12.75  # Socks

# Calculate subtotal
subtotal = item1_price + item2_price + item3_price

# Apply 10% discount for students
discount_rate = 0.10
discount_amount = subtotal * discount_rate
discounted_total = subtotal - discount_amount

# Calculate tax on discounted amount (8.5% sales tax)
tax_rate = 0.085
tax_amount = discounted_total * tax_rate
final_total = discounted_total + tax_amount

# Display receipt
print("=== SHOPPING CART RECEIPT ===")
print("Subtotal: $", round(subtotal, 2))
print("Discount (10%): $", round(discount_amount, 2))
print("Discounted total: $", round(discounted_total, 2))
print("Tax (8.5%): $", round(tax_amount, 2))
print("Final total: $", round(final_total, 2))
print("Thank you for shopping with us!")

# TODO: Add support for multiple quantities
# TODO: Add item names to the receipt

Final Exercise: Create Your Own Well-Commented Program

Create a program that calculates the time needed to read a book. Include a multi-line comment describing the program and single-line comments explaining the calculations.

# TODO: Add a multi-line comment describing what this program does book_title = "The Python Guide" total_pages = 250 pages_per_minute = 2 # TODO: Add comment explaining the time calculation reading_time_minutes = total_pages / pages_per_minute # TODO: Add comments explaining the hour/minute conversion hours = reading_time_minutes // 60 remaining_minutes = reading_time_minutes % 60 print("Book:", book_title) print("Total pages:", total_pages) print("Reading speed:", pages_per_minute, "pages per minute") print("Time needed:", reading_time_minutes, "minutes") print("That's about", int(hours), "hours and", int(remaining_minutes), "minutes!")

📝 What You've Learned

Congratulations! You now understand how to use comments effectively in Python:

Comments are like leaving breadcrumbs for your future self - they'll help you understand your code weeks or months later. Good commenting is a sign of a thoughtful programmer!

Next Steps

Now that you know how to document your code with comments, you're ready to learn about actually making your code do things with the print function!