How to comment out multiple lines in python

How to comment out multiple lines in python

In this article, we will see about how to comment out multiple lines in python.

The concept of comments is present in most programming languages. We use comments for documentation purposes. The compiler ignores them, but the user can use comments to describe what is happening in the code.

As the code grows longer and becomes more complicated, comments prove to be a good way of explaining the code.

In Python, we use the # character to initiate a comment. We use this for declaring single-line comments.

Most programming languages support multi-line comments also. However, in Python, we can only have one-line comments. We cannot directly comment out multiple lines as comments in Python.

Multiple Line Comments in Python

We will discuss how to emulate such multiple-line comments in this article.

Using the # character

To have multiple line comments, we can declare a single-line comment in every line. This method is tedious but works nevertheless.

For example,

Using triple quotes

Using triple quotes, we can create multi-line strings in Python. It is a good way to emulate multi-line comments, but one must be careful about the indentation.

For example,

In the above example, we can see that such strings successfully emulate multi-line comments. However, if one is not careful, they might turn into accidental docstrings.

A docstring conveys the working and description of a function, module, or any other object. We declare them right after defining the function or at the start of the module.

However, we can also hide this string in context and prevent them from being mistaken as docstrings.

See the code below.

Let us understand the above code. The if False: statement will never execute, so we hide the docstring in plain sight.

Using IDEs and Text Editors

Some IDEs and editors allow us to comment out blocks. On JetBrains PyCharm, we can select the code block and use control + / key to comment it. Similarly, the combination of control + k can comment out a code block in Python Tools for Visual Studio.

That’s all about how to comment out multiple lines in python.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *