Is There A Way To Create Multiline Comments In Python?

Summary: You can use consecutive single-line comments (using # character) to create a block of comments (multiline comments) in Python. Another way is to use """ quotes to enclose the comment block.


Problem Statement: How to create multiline comments in Python?

Other programming languages like C++, Java, and JavaScript, have an inbuilt mechanism (block comment symbols) for multiline comments, but there is no built-in mechanism for multiline comments in Python. Hence, the following code won’t work:

/*
This is a multiline
Comment in
Python
*/

The above code will throw an error in Python. However, there are still some workarounds to using the multiline comments in Python. Let’s look at the different methods to do this in this article.

  • Quick Trivia on Comments:
    • Comments are a very important part of every programming language as it explains the logic used in the code. The developers provide these comments to make it more readable and for the users to get a better understanding of the code. The comments don’t run as they are ignored by the interpreters and compilers. Comments also help us while we are debugging, i.e., when there are two lines of code, we can comment one out to prevent it from running.
  • What is a multiline comment in Python?
    • A multiline comment in Python is a comment that generally expands to multiple lines, i.e., multiline comments are the comments that expand to two or more lines in the source code.

Method 1: Using Multiple Single Line Comments

We can use the multiple single-line comments to create multiline comments in Python. But first, you must know how to make a single-line comment is in Python. The Hash character (#) is used to make single-line comments in Python. The commented line does not get printed in the output.

Example:

# print("Hello Finxters")
print("Learning to create multiline comments in Python")

Output:

Learning to create multiline comments in Python

Now let’s create multiline comments using consecutive single line comments:

Example:

print("Learning to create multiline comments in Python")
# print("Hello Finxters")
# print("This is a")
# print("Multiline comment")
# print("in Python")
print("End of program")

Output:

Learning to create multiline comments in Python
End of program

As we can see that the commented lines are ignored by the parser in Python, thereby creating a block of comments.

Discussion: Using single-line comments to comment out every line of a multiline comment individually becomes a very tedious process. Hence this method is not recommended to be used when you are not using any modern editor. However, most of the new code editors have a shortcut for block commenting in Python. You can just select a few lines of code using shift and the cursor keys and then press cmd + / (This shortcut may differ depending upon the editor you are using) to comment them out all at once. You can even uncomment them easily by simply selecting the block of comments and pressing the cmd + / keyboard shortcut.

Method 2: Using Docstrings Or Multiline Strings

We can create the multiline comments using multiline strings or docstrings in Python. This method has the same effect but is generally used for documentation strings, not block comments. However, if you want to comment things out temporarily, you can use this method. Python has two types of docstrings-
1) One-Line docstrings
2) Multiline docstrings.

To create a block comment, we use the multiline docstrings. Let’s create multiline comments using docstrings in the following example:

Example 1:

print("Learning to create multiline comments in Python")
'''
print("Hello Finxters")
print("This is a")
print("Multiline comment")
print("in Python")
'''
print("End of program")

Output:

Learning to create multiline comments in Python
End of program

Example 2: Suppose you want to define a block comment inside a function using docstrings you have to do it the following way:

def multiply(x, y):
    res = x * y
    """
    This is a multiline comment indented properly
    This function returns the result
    after multiplying the two numbers
    """
    return res
print("The multiplication of the two numbers is", multiply(10, 5))

Output:

The multiplication of the two numbers is 50
  • Caution:
    • You must always ensure that you have used the indentation for the first """ correctly; otherwise, you may get a SyntaxError.
    • Also, if you are opening a multiline comment using three double quotes """ then you must ensure that you enclose the block with exactly three double quotes as well. If you do nt follow this convention, you will get an error again. For example – if you open a multiline comment with three double quotes and close it using three single quotes, then you will get an error.

Example I: If you don’t intend """ properly, you may get the following error:

def multiply(x, y):
    res = x * y
"""
    This is a multiline comment indented properly
    This function returns the result
    after multiplying the two numbers
    """
    return res
print("The multiplication of the two numbers is", multiply(10, 5))

Output:

File "main.py", line 10
    return res
    ^
IndentationError: unexpected indent

Example II: Let’s visualize what happens when there is a mismatch between the type of triple quotes used.

def multiply(x, y):
    res = x * y
    """
    This is a multiline comment indented properly
    This function returns the result
    after multiplying the two numbers
    '''
    return res
print("The multiplication of the two numbers is", multiply(10, 5))

Output:

  File "C:\Users\SHUBHAM SAYON\PycharmProjects\Finxter\General\rough.py", line 10
    print("The multiplication of the two numbers is", multiply(10, 5))
                                                                      ^
SyntaxError: EOF while scanning triple-quoted string literal

Note: You must always be careful where you place these multiline comments in the code. If it is commented right after a class definition, function, or at the start of a module, it turns into a docstring that has a different meaning in Python.

Example:

def multiply(x, y):
    """
    This is a multiline comment made 
    right after the function definition
    It now becomes a function docstring associated
    with the function object that is also 
    accessible as runtime metadata
    """
    res = x * y
    return res
print("The multiplication of the two numbers is", multiply(10, 3))

Output:

The multiplication of the two numbers is 30

🖋️The difference between the comment and the parser is that the comment is removed by the parser, whereas a docstring can be accessed programmatically at runtime and ends up in the byte code. 

Conclusion

Therefore, in this tutorial, we learned two ways of creating multiline comments in Python –
➨Using consecutive single-line comments.
➨Multiline strings (docstrings).

That’s all for this article. I hope you found it helpful. Please stay tuned and subscribe for more interesting articles and tutorials in the future. Happy learning!

🖋️Authors: Rashi Agarwal and Shubham Sayon


Recommended Read: