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.

  1. Adding the # symbol manually before each line.

  2. Using docstrings.

Manually adding # before each line

# Calculate the sum of squares for a range of numbers.
# Initialize a variable named total_squares to zero.
# Iterate over a range of numbers from 1 to 5 using a for loop.
# In each iteration, calculate the square of the current number and add it to # total_squares.
# After the loop, display the result.

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:

"This is a single-line docstring"

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.

"""
Calculate the sum of squares for a range of numbers.
Initialize a variable named total_squares to zero.
Iterate over a range of numbers from 1 to 5 using a for loop.
In each iteration, calculate the square of the current number and add it to total_squares.
After the loop, display the result.
"""
# Loop for calculating the sum of squares
total_squares = 0
for i in range(1, 6):
square = i**2
total_squares += square
# Displaying the result
print(f"The sum of squares from 1 to 5 is: {total_squares}")

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.