How to comment multiple lines in Python?

In this tutorial, we will learn if and how you can comment multiple lines in Python.

Before we dive into this tutorial, let us first understand what a comment is.

Whenever you buy a device, you must have noticed that it comes with a manual. The manual contains a brief description of the device for you to understand the device and its usage.
A comment is to a program what a manual is to devices. It is a brief explanation of the code provided by the developer to help the reader understand the code and what it does, thereby also improving the readability.

Multi-line comments in Python

Different programming languages have different syntaxes for defining both single-line and multi-line comments. However, Python has no syntax reserved for writing a multi-line comment.
We can comment multiple lines in Python in two ways which are explained below.

Inserting # in each line(i.e consecutive single line comments)

Single-line comments in Python are defined using the #symbol as shown.

#Command to print hello
print("Hello")
Hello

Though Python has no syntax for defining a multi-line comment, we can insert the #symbol in each line to achieve multi-line commenting.
Since this is not very efficient, some of the text editors like VS Code, Sublime Text Editor etc even provide shortcuts for the same.
For example, you can select the lines to be set as multi-line comments and then press control+/ keys in Jupyter Notebook.
This can be demonstrated as shown.

#Command to print hello
#Command to ask how are you 
print("hello")
print("how are you?")
hello
how are you?

Using multi-line string (triple-quoted string)

You must be aware of the usage of triple quoted strings(“”” “””) to span strings of multiple lines. However, what’s interesting is that the same can be used for writing multi-line comments.
Python ignores string literals if they have not been assigned to any variables. We make use of this to achieve multi-line comments.
When we enclose our multi-line comment within triple quotes, though Python reads the code, it will ignore it by considering it to be a string literal that does nothing as shown below.

"""
Command to print hello
print("hello")
Command to ask how are you 
print("how are you?")
"""
print("hello")
print("how are you?")
hello
how are you?

Note:

  1. No spaces are to be inserted between the quotes.
  2. You must be careful to not use the above method immediately after a class or a function, in which case Python will consider it to be a docstring.
    You can read more about Python Docstrings at Python Docstrings

Hope this helped! 🙂

 

Leave a Reply

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