💬 Writing Comments
Comments are notes you write in your code to explain what it does and why. They're like leaving helpful messages for yourself and other programmers who might read your code later. Python ignores comments completely when running your program, so you can write as many as you need!
Good comments make your programs easier to understand, debug, and maintain. Think of them as documentation that travels with your code.
# This is a single-line comment
print("Hello, World!") # Comments can go at the end of lines too
# Comments help explain what your code does
name = "Alice"
age = 25
# Calculate birth year (approximate)
current_year = 2024
birth_year = current_year - age
print(f"{name} was probably born in {birth_year}")
📝 Types of Comments in Python
Python offers different ways to add comments to your code. Understanding when to use each type helps you document your programs effectively.
📄 Single-Line Comments (# symbol)
The # symbol creates single-line comments. Everything after #
on that line is ignored by Python.
# This is a single-line comment
print("Hello, Python!")
age = 25 # You can add comments at the end of lines
# Comments help explain your code
📃 Multi-Line Comments
For longer explanations, you have two options:
- Triple quotes
"""
or'''
(often used for function documentation) - Multiple # lines (more common for regular comments)
"""
This is a multi-line comment using triple quotes.
It can span several lines and is useful for
longer explanations or documentation.
"""
# You can also use multiple single-line comments
# to explain more complex concepts
# across several lines
name = "Python"
print(f"Hello, {name}!")
🎯 When to Write Comments
Good comments explain the "why" behind your code, not just the "what". Here's when comments add real value:
🧠 Explain Complex Logic
When your code does something that isn't immediately obvious, explain it!
# Calculate tip amount for restaurant bill
bill = 45.50
tip_percentage = 18
# Convert percentage to decimal and calculate tip
tip = bill * (tip_percentage / 100)
total = bill + tip
print(f"Bill: ${bill}")
print(f"Tip ({tip_percentage}%): ${tip:.2f}")
print(f"Total: ${total:.2f}")
💡 Document Your Intentions
Explain why you chose a particular approach or what the code is trying to accomplish:
# Check if user age is reasonable (between 0 and 120)
age = int(input("Enter your age: "))
if 0 <= age <= 120:
print("Valid age entered")
# Calculate approximate birth year
# Note: This doesn't account for exact birth date
birth_year = 2024 - age
print(f"You were probably born in {birth_year}")
else:
print("Please enter a realistic age")
📊 Explain Business Rules
When your code implements specific rules or formulas, explain them:
# Convert temperature from Celsius to Fahrenheit
# Formula: F = (C × 9/5) + 32
celsius = 25
fahrenheit = (celsius * 9/5) + 32
print(f"{celsius}°C = {fahrenheit}°F")
✍️ Writing Good Comments
Good comments are clear, helpful, and add value to your code. Here's how to write them effectively:
🤔 Focus on "Why", Not "What"
Good comments explain the purpose and reasoning:
# Good comment: Explains WHY
# Use a discount for bulk purchases over $100
total = 150
if total > 100:
discount = total * 0.1 # 10% discount for bulk orders
total = total - discount
print(f"Final total: ${total:.2f}")
🔍 Be Clear and Concise
Use simple language that anyone can understand:
# Calculate total price including tax
price = 29.99
tax_rate = 0.08 # 8% sales tax
tax_amount = price * tax_rate
total = price + tax_amount
print(f"Price: ${price}")
print(f"Tax: ${tax_amount:.2f}")
print(f"Total: ${total:.2f}")
🔄 Keep Comments Updated
Important: Always update comments when you change your code! Outdated comments are worse than no comments.
Comment Examples: Good vs Bad
Let's see the difference between helpful and unhelpful comments:
👍 Examples of Good Comments
# Good comments explain purpose and context
# Generate a simple password for demonstration
# (Not secure - don't use in real applications!)
name = "Alice"
birth_year = 1995
lucky_number = 7
password = name[0] + str(birth_year) + str(lucky_number)
print(f"Generated password: {password}")
# Calculate compound interest
# Formula: A = P(1 + r)^t
principal = 1000
rate = 0.05 # 5% annual interest
time = 2 # 2 years
amount = principal * (1 + rate) ** time
print(f"After {time} years: ${amount:.2f}")
👎 Examples of Bad Comments
# Bad comments state the obvious
# x = 5 # BAD: Set x to 5 (obvious!)
# print(x) # BAD: Print x (obvious!)
# Better approach - only comment when it adds value
x = 5 # Maximum retry attempts
print(x)
Commenting Different Code Structures
As your code becomes more complex, different structures need different commenting approaches:
📝 Commenting Functions
When you start writing functions, document what they do:
def calculate_tip(bill_amount, tip_percentage):
"""
Calculate the tip amount for a restaurant bill.
bill_amount: The total bill before tip
tip_percentage: The tip percentage (e.g., 15 for 15%)
Returns the tip amount
"""
tip = bill_amount * (tip_percentage / 100)
return tip
# Use the function
bill = 45.00
tip_percent = 18
tip_amount = calculate_tip(bill, tip_percent)
print(f"Tip: ${tip_amount:.2f}")
📑 Commenting Code Sections
Use comments to organize your program into sections:
# ===== USER INPUT SECTION =====
print("Restaurant Tip Calculator")
bill = float(input("Enter bill amount: $"))
tip_percent = float(input("Enter tip percentage: "))
# ===== CALCULATION SECTION =====
tip_amount = bill * (tip_percent / 100)
total_amount = bill + tip_amount
# ===== OUTPUT SECTION =====
print(f"Bill: ${bill:.2f}")
print(f"Tip ({tip_percent}%): ${tip_amount:.2f}")
print(f"Total: ${total_amount:.2f}")
💡 Comment Best Practices
Follow these practices to write professional, helpful comments:
1️⃣ Write Comments While Coding
Don't wait until later—write comments as you code when your thinking is fresh.
2️⃣ Use Consistent Style
Pick a style and stick to it throughout your program:
# Consistent comment style example
# Calculate student grade average
math_score = 85
english_score = 92
science_score = 78
# Find the average of all three scores
average = (math_score + english_score + science_score) / 3
# Determine letter grade based on average
if average >= 90:
letter_grade = "A"
elif average >= 80:
letter_grade = "B"
else:
letter_grade = "C"
print(f"Average: {average:.1f} - Grade: {letter_grade}")
3️⃣ Avoid Over-Commenting
Don't comment every single line—focus on the important parts:
# Good balance of comments
# Student grade calculator
student_name = "Alice"
scores = [85, 92, 78, 95, 88]
# Calculate average (sum all scores, divide by count)
total = sum(scores)
average = total / len(scores)
# Display results
print(f"Student: {student_name}")
print(f"Average: {average:.1f}")
📋 Key Comment Rules Summary
Rule | Example | Why Important |
---|---|---|
Use # for single-line | # This explains the code | Standard Python comment syntax |
Explain WHY, not WHAT | # Apply discount for bulk orders | Adds actual value |
Keep comments updated | Update when code changes | Prevents confusion |
Use clear language | Simple words everyone understands | Makes code accessible |
Don't state obvious | Avoid x = 5 # Set x to 5 | Reduces clutter |
🧠 Test Your Knowledge
Ready to test your understanding of writing effective comments?
🚀 What's Next?
Great job! You now know how to document your code with helpful comments. Good commenting habits will make you a better programmer and help others understand your code.
Next, we'll explore one of the most fundamental programming concepts: variables!
Continue to: Working with Variables
Keep writing clear, helpful comments! 📝
Was this helpful?
Track Your Learning Progress
Sign in to bookmark tutorials and keep track of your learning journey.
Your progress is saved automatically as you read.