Course contentsShow
← Python
Lesson 60 of 1,0601. Foundations and EnvironmentFree lesson

Implementing Effective Inline and Block Comments

Learners will identify when to use comments to explain the 'why' behind complex logic rather than describing the 'what' already visible in code.

Mastering Comments: Explaining the 'Why'

In this lesson, you will learn how to write comments that provide meaningful context for your code rather than simply repeating what the code already says.

When you write code, it is tempting to use comments to describe every single action, like this:

# Add 1 to the counter
counter += 1

This is considered "noise." Any programmer reading this can see that counter += 1 adds one to the counter. Instead, we use comments to explain the why—the intent or the logic behind complex decisions that aren't immediately obvious.

Block Comments for Context

Use block comments (a paragraph of comments starting with #) to explain the goal of a complex chunk of code. Place these above the section they describe.

# We adjust the user's score based on the 'bonus' flag. 
# This ensures that early adopters receive the 10% loyalty reward 
# as per the updated marketing requirements.
if is_early_adopter:
    score += 10

Inline Comments for Sharp Logic

Inline comments sit on the same line as your code, separated by at least two spaces. Use these sparingly to clarify a specific, tricky line of logic.

x = x * 1.05  # Apply 5% tax rate mandated by regional policy

The Golden Rule

Ask yourself: "If I read this in six months, would I be confused about why this logic exists?" If the answer is yes, write a comment. If the code is self-documenting (like a well-named variable or a simple math operation), let the code speak for itself. You want your comments to act as a "secret" map of your thought process, not a mirror of the code itself.

Key Takeaway: Use comments to explain the "why" behind your logic so future readers—including your future self—understand the intent behind your decisions.