How to Comment Out a Block of Code in Python?

In this tutorial, let us understand how to comment out a block of code in Python. As a developer working on a project for a US-based company, I recently encountered a situation where I needed to temporarily disable a section of my Python script without deleting it entirely. That’s when I discovered the power of commenting out code blocks in Python. Let us see how it works.

Comment Out Code

Commenting out code means temporarily disabling a portion of your script by turning it into a comment. This is useful when you want to test different variations of your code, troubleshoot issues, or simply save a block of code for later.

Read Interfaces in Python

Single-Line Comments in Python

In Python, you can create single-line comments by prefixing a line with the hash symbol (#). Here’s an example:

# This is a single-line comment
print("Hello, John from New York!")

In this case, the line # This is a single-line comment is ignored by the Python interpreter, and only the print statement is executed.

Read Access Modifiers in Python

Comment Out a Block of Code in Python

When you need to comment out multiple lines of code in Python, you have a couple of options:

  1. Prefixing each line with the hash symbol (#)
  2. Using triple quotes (""" or ''') to create a multi-line comment

Method 1: Prefix Each Line with Hash (#)

One way to comment out a block of code is to prefix each line with the hash symbol (#).

Here’s an example:

# def greet(name):
#     print(f"Hello, {name}!")
#
# greet("Sarah from California")

I have shown you how will a commented line look in the below screenshot.

Comment Out a Block of Code in Python

In this case, the entire function definition and function call are commented out.

Method 2: Use Triple Quotes (""" or ''')

Another approach is to use triple quotes (""" or ''') to create a multi-line comment. Here’s an example:

"""
def calculate_total(prices):
    total = sum(prices)
    return total

cart_prices = [10.99, 5.99, 8.49]
total_price = calculate_total(cart_prices)
print(f"The total price is: ${total_price:.2f}")
"""

I have shown you how will a commented line look in the below screenshot.

How to Comment Out a Block of Code in Python

In this example, the entire block of code, including the function definition, variable assignments, and print statement is commented out using triple quotes.

Read How to Use Single and Double Quotes in Python?

Keyboard Shortcuts to Comment Out Code in Python

Most IDEs and text editors provide keyboard shortcuts to quickly comment out a block of code. Here are a few common shortcuts:

  • Windows/Linux: Ctrl + /
  • macOS: Cmd + /

By selecting the lines you want to comment out and using these shortcuts, you can easily comment the lines.

Read Python 3 vs Python 2 [Key Differences]

Best Practices to Comment Out Code in Python

When commenting out code, keep the following best practices in mind:

  1. Use meaningful comments to explain why you’ve commented out a specific block of code.
  2. Avoid leaving commented-out code in your final production script. Remove unnecessary comments before deploying your code.
  3. If you need to save a block of code for later use, consider moving it to a separate file or version control system instead of leaving it commented out in your main script.

Read Difference Between “is None” and “== None” in Python

Example

Let’s say you’re working on a Python script that generates reports for a US-based e-commerce company. You have a function that calculates the sales tax based on the state, but you want to temporarily disable it for testing purposes. Here’s how you can comment out the relevant block of code:

def calculate_order_total(subtotal, state):
    # if state == "CA":
    #     tax_rate = 0.0725
    # elif state == "NY":
    #     tax_rate = 0.08875
    # else:
    #     tax_rate = 0.0
    #
    # tax = subtotal * tax_rate
    # total = subtotal + tax

    total = subtotal  # Temporarily disable tax calculation
    return total

order_subtotal = 149.99
customer_state = "CA"
order_total = calculate_order_total(order_subtotal, customer_state)
print(f"Order total: ${order_total:.2f}")

In this example, the tax calculation logic is commented out using the hash symbol (#), and a temporary line total = subtotal is added to calculate the order total without taxes. This allows you to test the rest of the script without the tax calculation.

Conclusion

In this tutorial, I have explained how to comment out a block of code in Python which allows you to temporarily disable portions or save code for later use. By using single-line comments (#) or multi-line comments (""" or '''). I explained shortcuts for commenting out code in Python, some best practices for comment code, and also a real-world example.

You may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.