How to Comment Out a Block of Code in Python

To comment out a block of code or multiple lines in Python, prepend each line with a # (octothorpe) or enclose the block within triple quotes ( ‘ ‘ ‘ or ” ” “).

This approach ensures that the specified text is not executed as part of the code.

Method 1: Using # for Commenting Multiple Single Lines

Everything following the # on that line will be treated as a comment and not executed.

Visual representation

Using # for Commenting Multiple Single Lines

Example

# This is block comment 
# Created using # symbol 
# This is the perfect example

print ("Block Comment in Python")

Output

Block comment in Python

Method 2: Using Triple-Quoted String Literals for Multi-Line Comments

The triple-quoted( ‘ ‘ ‘ or ” ” “) strings can be used to create multi-line string literals, but they’re often used as a way to comment out large blocks of code.

Visual representation

Using Triple-Quoted String Literals for Multi-Line Comments

Example

"""
This is a multi-line comment
Using triple-quoted string literals
In Python
"""

print ("Multi-line comments using triple quotes")

Output

Multi-line comments using triple quotes

Further reading

How to Create a Comment Block on Jupyter Notebook

How to Create a Comment Block on VSCode in Python

5 thoughts on “How to Comment Out a Block of Code in Python”

  1. But wanna comment on few general things, The website style and design is perfect, the written content is rattling superb : D.

    Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.