Multiline comments in Python
Python Comments is used for the non-executable statement, it helps to make the code readable. And multiline comments in Python a multiple line of comments.
Ways to achieve multiline comments in Python
- Consecutive single-line comment
- Using a Multi-line string as a comment
Consecutive single-line comment
Hash character(#) is used to comment the line in the Python program. Comments does not have to be text to explain the code, it can also be used to prevent Python from executing code.
The hash character should be placed before the line to be commented. Consecutive single-line comments can be used as multiline comments in Python.
Example: How to Make Single Line Comments in Python
Python3
# Write Python3 code here# Single line comment usedprint("Python Comments")# print("Mathematics") |
Output:
Python Comments
Here, the first two lines contain hash character(#) and the interpreter prevents the two lines from execution. Then it prints the “Python Comments” and finally, it will prevent the last line from execution.
Using a Multi-line string as a comment
Python multi-line comment is a piece of text enclosed in a delimiter (“””) on each end of the comment. Again there should be no white space between delimiters (“””).
They are useful when the comment text does not fit into one line; therefore needs to span across lines. Multi-line comments or paragraphs serve as documentation for others reading your code. See the following code snippet demonstrating multi-line comment:
Example: How to Make Multi-line Comments in Python
Python3
# Write Python code here""" Multi-line comment usedprint("Python Comments") """print("Mathematics") |
Output:
Mathematics
In the above example, multi-line comments are used to comment on more than one line. The first line is a single-line comment. The second and third lines can be commented on using triple quotes(“”” “”””). This prevents the execution of the above code. Finally, it prints “Mathematics” in the output. However, if these multiline comments are placed directly after a function or class signature, then these turn into docstrings.
Docstring is an in-built feature of Python, which is used to associate documentation that has been written with Python modules, functions, classes and methods. It is added right below the functions, modules, or classes to describe what they do. In Python, the docstring is then made available via the __doc__ attribute.
Example:
Python3
def multiply(a, b): """Multiplies the value of a and b""" return a*b # Print the docstring of multiply functionprint(multiply.__doc__) |
Output:
Multiplies the value of a and b


