DEV Community

Cover image for Python Comments - Write Code Humans Can Actually Understand
Aaron Rose
Aaron Rose

Posted on

Python Comments - Write Code Humans Can Actually Understand

You’ve written a brilliant piece of Python code. It works perfectly. You close your laptop, proud of your work.

Fast forward three months. You reopen the file to add a new feature and suddenly think: “What on earth was I doing here? Why did I do it this way?”

We’ve all been there. This is where comments come to the rescue. Think of them as sticky notes for your code—little messages for your future self and other developers to explain not just what your code does, but why you wrote it that way.

Let’s break down the simple art of Python commenting.

The Three Types of Python Comments

Python gives us three straightforward ways to leave notes in our code.

1. Inline Comments
These live on the same line as your code, after a # symbol. They’re great for quick, one-line explanations.

# Good inline comments:
radius = 5  # Radius in centimeters
area = 3.14 * radius**2  # Calculate area using πr²
print(area)  # Debug: output the result to verify
Enter fullscreen mode Exit fullscreen mode

2. Block Comments
These are longer notes that span multiple lines, each starting with a #. Use them to explain a whole section of code that’s coming up.

# This function calculates the final price after applying
# a discount and regional tax. It handles rounding to
# avoid floating-point arithmetic issues with currency.
def calculate_total(price):
    # ...the actual code goes here
Enter fullscreen mode Exit fullscreen mode

3. Docstrings
These are the super-powered comments, wrapped in triple quotes """. They’re used right under a function, class, or at the top of a file to explain what it does, what parameters it takes, and what it returns.

def calculate_discount(price, discount_percent):
    """
    Applies a discount to a price and returns the new amount.

    Args:
        price (float): The original price of the item.
        discount_percent (float): The discount to apply (e.g., 20.0 for 20%).

    Returns:
        float: The discounted price.
    """
    return price * (1 - discount_percent / 100)
Enter fullscreen mode Exit fullscreen mode

The "Aha!" Moment: With vs. Without Comments

Let’s look at the difference a few comments can make.

Without Comments: 🤨

def process_data(data):
    if not data:
        return None
    temp = []
    for d in data:
        if d % 2 == 0:
            t = d * 2
            temp.append(t + 10)
    return sorted(temp)[-1]  # Inefficient: sorting just to find the max
Enter fullscreen mode Exit fullscreen mode

What is this even doing? It’s a puzzle.

With Comments: 😍

def process_data(data):
    """Finds the highest processed value from even numbers in the dataset."""
    if not data:
        return None
    processed_values = []
    for number in data:
        if number % 2 == 0:  # Only process even numbers
            # Business rule: double the number and add 10
            processed_value = number * 2 + 10
            processed_values.append(processed_value)
    # Return the highest resulting value
    return max(processed_values)  # More efficient than sorted()[-1]
Enter fullscreen mode Exit fullscreen mode

See? Instantly clearer. The comments explain the logic, the purpose, and even note the improved efficiency.

The Golden Rule of Commenting

The best advice you’ll ever get about comments is this simple mantra:

“Write why, not what.”

The code itself shows what is happening. Your comments should explain why it’s happening.

  • ❌ Don't write: x = x + 1 # Add 1 to x (This is obvious!)
  • ✅ Do write: index = index + 1 # Skip the first header row in the data (This is helpful!)

When to Hold Back

Not every line needs a comment. The biggest beginner mistake is commenting too much on what's obvious. If the code is self-explanatory, a comment is just noise. A good rule of thumb is that if a programmer with a basic understanding of Python can't figure out what a line does, then it might be time for a comment.

Example of what to avoid:

# This variable stores the user's name
user_name = "Alice"
Enter fullscreen mode Exit fullscreen mode

This comment is completely unnecessary—the variable name user_name already tells us what it does.

Your New Superpower

Adding clear, thoughtful comments is one of the kindest things you can do for your fellow developers—and for your future self. It transforms your code from a mere set of instructions into a readable story.

Now go forth and comment! Your future self will thank you.


Next Step: Ready to level up? In our next post, we’ll look at the Secret Art of Writing Great Python Comments and dive into the best practices that make comments truly shine.


Aaron Rose is a software engineer and technology writer at tech-reader.blog and the author of Think Like a Genius.

Top comments (1)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.