If you’ve ever revisited your own code after a few months, you probably know the pain of trying to remember why you wrote something the way you did. That’s where comments come in—they’re your future self’s best friend and a lifeline for anyone who needs to understand your code. In Python, multi-line or block comments are particularly useful for explaining complex logic, documenting workflows, and making your code approachable for others. This guide dives into everything you need to know about mastering block comments in Python while keeping things clear and approachable.


Table of Contents

Single-Line vs. Multi-Line Comments: When to Use Each

Best Practices for Writing Block Comments

Real-World Example: Documenting a Machine Learning Pipeline


Single-Line vs. Multi-Line Comments: When to Use Each

Python gives you two main ways to comment on your code: single-line comments and multi-line (or block) comments. Knowing when and how to use each is key to writing clear, maintainable code.

Single-Line Comments

Single-line comments are created using the # symbol. They’re perfect for quick explanations or to clarify something specific about a single line of code.

python

x = 42  # Assign the answer to life, the universe, and everything

Think of single-line comments like sticky notes: short, direct, and to the point. Use them to highlight why something is done, especially if the code itself doesn’t make it immediately obvious.


Multi-Line (Block) Comments

Sometimes, a quick sticky note just doesn’t cut it—you need a full paragraph. That’s where multi-line comments shine. They allow you to explain entire sections of code, which is especially useful for workflows, complex algorithms, or parts of your project that might not be intuitive to others.

There are two main ways to create block comments in Python:

Using # for Each Line

python

# This function calculates the factorial of a number

# using recursion. If the input is negative, it raises

# a ValueError to prevent invalid operations.

def factorial(n):

    if n < 0:

        raise ValueError("Input must be non-negative")

    return 1 if n == 0 else n * factorial(n - 1)
  1. This approach is simple, clear, and works perfectly for documenting larger chunks of logic. It’s also ignored entirely by the Python interpreter, so you don’t have to worry about any performance impact.

Using Triple Quotes (“”” “”” or ”’ ”’) Triple-quoted strings are technically string literals—not comments. If not assigned to a variable or used as a docstring, they still exist in memory as no-op strings. While they can act as block comments, it’s best to use them for their intended purpose: docstrings.

python

"""

This function processes a list of user inputs:

- It validates the inputs, ensuring they are integers.

- It removes duplicates and sorts the results.

"""

def process_inputs(inputs):

    validated_inputs = [i for i in inputs if isinstance(i, int)]

    return sorted(set(validated_inputs))
  1. Pro Tip: Use triple quotes for documenting functions, classes, and modules, especially when the documentation is part of the public API. These docstrings are accessible through Python’s built-in help() function, making them incredibly useful for others (and your future self) when navigating your code.


Best Practices for Writing Block Comments

Effective comments don’t just describe code—they explain why the code is written a certain way. They give context, outline assumptions, and help anyone reading your code understand your thought process. Here’s how to write block comments that make your code truly readable:

  1. Explain the Why, Not the What
    Don’t just repeat what the code does—focus on why it’s doing it. For example:
python

# Correct example:

# We add 1 to the index here because the loop starts at 0, 

# but the data structure expects a 1-based index.

index += 1

# Avoid:

# Add 1 to index

index += 1  # This is redundant.
  1. Keep It Clear and Concise
    Block comments are for clarity, not essays. Aim to provide enough information to make the code understandable without overwhelming the reader.
  2. Keep Comments Up-to-Date
    Outdated comments can lead to major confusion, so make sure your comments evolve as your code changes.
  3. Avoid Over-Commenting
    Don’t comment on every single line—it makes your code more challenging to read, not easier. Strike a balance and comment only where it’s genuinely helpful.

Real-World Example: Documenting a Machine Learning Pipeline

Let’s put this into action. Imagine you’re building a machine learning pipeline to process data, train a model, and evaluate its performance. This kind of workflow can get pretty complex, so clear comments are crucial.

Here’s how you might use block comments to document the pipeline:

python

# Import necessary libraries

# Grouping all imports at the top improves code readability and follows Python conventions.

import pandas as pd

from sklearn.preprocessing import MinMaxScaler

from sklearn.model_selection import train_test_split

from sklearn.ensemble import RandomForestClassifier

from sklearn.metrics import accuracy_score

# Step 1: Load and preprocess the dataset

# - Load data from a CSV file.

# - Handle missing values by filling them with the mean. 

#   Note: Mean imputation assumes the data distribution is suitable for this approach.

# - Scale numerical columns to a range of 0 to 1 using MinMaxScaler 

#   to standardize feature values for improved model performance.

data = pd.read_csv("dataset.csv")

data.fillna(data.mean(), inplace=True)

scaler = MinMaxScaler()

data[["feature1", "feature2", "feature3"]] = scaler.fit_transform(data[["feature1", "feature2", "feature3"]])

# Step 2: Split the data into training and testing sets

# Use an 80-20 split to evaluate how well the model generalizes to unseen data.

# random_state=42 ensures reproducibility of the results.

X = data.drop(columns=["target"])

y = data["target"]

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# Step 3: Train a Random Forest model

# Initialize the model with:

# - n_estimators=100: Balances accuracy and computational cost.

# - random_state=42: Ensures results are reproducible.

model = RandomForestClassifier(n_estimators=100, random_state=42)

model.fit(X_train, y_train)

# Step 4: Evaluate the model

# Calculate accuracy as a performance metric. 

# Note: For imbalanced datasets, consider metrics like precision, recall, or F1-score.

y_pred = model.predict(X_test)

accuracy = accuracy_score(y_test, y_pred)

print(f"Model accuracy: {accuracy:.2f}")

Wrapping It Up: Best Practices in Action

Block comments are your opportunity to make your code accessible and maintainable. By writing comments that focus on why decisions were made, keeping them concise, and using the appropriate tools for the job (# for comments and triple quotes for docstrings), you can make your Python code a joy to work with—for yourself and for anyone who follows in your footsteps.

Remember, good comments don’t just describe code—they make it approachable, collaborative, and future-proof. Whether you’re explaining a machine learning workflow or documenting a tricky algorithm, thoughtful comments are the bridge between code that works and code that shines. If you want to learn more about Python programming, check out our highly reviewed Introduction To Programming Nanodegree program. Happy coding!