How do we create multiline comments in Python?

Published on Aug. 22, 2023, 12:15 p.m.

Python does not have a built-in syntax for creating multiline comments. However, you can achieve the same effect by commenting out each line of the code block with a hash symbol (#). Here is an example:

# This is a multiline
# comment in Python
print("Hello, World!")

In this example, the hash symbol (#) is used to comment out each line of the multiline comment. The actual code that runs is print("Hello, World!").

Alternatively, if you want to temporarily disable a block of code, you can use triple quotes to create a multiline string literal. Here is an example:

"""
print("This code is commented out temporarily")
print("It will not run until the triple quotes are removed")
"""
print("Hello, World!")

In this example, the multiline string literal is used to comment out the two lines of code that are enclosed in the triple quotes. The actual code that runs is print("Hello, World!").

Note that using the triple quotes to comment out code in this way can be unwise, as it can lead to confusion and make it unclear whether the code is actually commented out or not.

Tags: