Multiline Comments
We'll cover the following...
Multiline comments
Python doesn’t offer symbols or a direct way to comment out multiple lines as with other languages. Still, there are two main ways we can do this with Python.
Adding the # symbol manually before each line.
Using docstrings.
Manually adding # before each line
Using docstrings
Developers often use docstrings instead of comments due to their efficient nature. Docstrings are Python strings mainly used for documenting functions, classes, or modules. They are typically added after a function definition. In Python, if a string literal is not stored in a variable, it doesn’t impact the code in any particular way, and therefore it can be used as a comment, although its original intent differs.
A single-line docstring is just like a string, such as the following, for instance:
However, docstrings are more helpful in multiline comments.
Let’s define a code that calculates the sum of squares for a given range. To explain how the code works, we can use a docstring above it and provide an explanation.
We enclose a single-line docstring between a pair of quotation marks ("..."), while we enclose a multiline docstring between a pair of three quotation marks ("""...""").
Note: On Visual Studio Code, we can use cmd + / to comment out multiple lines immediately. This shortcut puts ‘#’ before each selected line simultaneously.