Sometimes, you do not want to comment just a single line from your Python code but a couple of lines. Especially when you are debugging your code, you will generally comment two or more lines to see how your program executes.

As you know, going line by line, adding a hash (#) sign and then a space, can be pretty much ineffective and a waste of time. One thing you can do to do it much faster is to use a multiline comment, where you comment multiple lines of Python code at once.

Python comments can span multiple lines. You can use the multiline string, triple quotes, to comment multiple lines of Python code. Python ignores code inside triple quotes as it identifies the code as a comment. However, you should not assign this string literal to a variable. Otherwise, Python will not read it as a comment.

There are two different ways to comment multiple lines of code in Python:

  1. A slow method that involves adding a pound (#) sign at the start of each line.
  2. Using triple quotes to create a multiline string literal that is not assigned to any variable.

How to comment multiple lines in Python using the # sign

To comment multiple lines of Python code, follow these steps:

Step 1: Insert a # sign at the start of the line you want to insert a comment

#

Step 2: Start writing your comment after the # sign

# This is a comment in Python

Step 3: If you have already written some code, insert the # sign at the start of your comment

Let’s say you already have a line of code that you want to comment

...
return f"My name is {name}. I am {age} years old"

You can insert a comment at the start of the line

...
# return f"My name is {name}. I am {age} years old"

Or anywhere in the line that you want to comment out

...
return # f"My name is {name}. I am {age} years old"

Step 4: Insert another # sign to create a comment in the next line

After writing your first comment, you can do the same thing to insert multiple comments that span across more than one line of code in Python.

...
# return f"My name is {name}. I am {age} years old"
# Another comment here (next line)

Insert multiline comments in Python using the # sign is as easy as that. You only need to begin a new line with a pound # sign, and you can create unlimited comments spanning multiple lines.

How to comment multiple lines in Python using the unassigned string literals

Another way to create comments in your Python code is to use string literals. As Python does specifically ignore string literals that are not assigned to any variable, you can exploit this feature to create multiline comments.

So, here are the steps that you need to take to create comments that span across multiple lines:

Step 1: Insert triple quotes on a new line to open your multiline comment

Starting where you want to insert your multiline comment, add triple quotes and jump to the next line.

'''

Step 2: Create your multiline comments

Most programmers like to indent the multiline comments. So, insert an indent with two or four spaces and start typing your line of comment.

'''
    This is the first line of my multiline comment
    This is a second line of my comment
    This comment is the third one and has an indent like all the others

Step 3: Close your multiline comment with another triple quote

'''
    This is the first line of my multiline comment
    This is a second line of my comment
    This comment is the third one and has an indent like all the others

'''

That’s it, run your program, and Python should ignore the code within your triple quotes.

You should take care not to assign string literals that you intend to be multiline comments in your Python. When you do assign multiline comment string literal to a variable, they are not ignored by Python.

Here is an example that you could make with string literal that are intended to be multiline comments:

myclass =  '''

class LessThanZeroError(Exception):
    def __init__(self, value):
        self.value = value
    
my_num = int(input("enter number: "))

if my_num:
    raise LessThanZeroError("My num must be greater than 0")
else:
    print("my_num", my_num)
    
    '''
    
print(myclass)

Instead of creating a comment, I have created a myclass variable that is treated as part of the code that Python executes.

Reasons why you will need to comment your Python code

  1. Make notes or human-readable descriptions for your code blocks, making your code readable. Besides, it makes it easier for your and other programmers to understand what your code does. Also, it makes your code easy to debug.
  2. Prevent execution of certain blocks or lines of code in your program
  3. Useful when debugging because you can execute line by line and avoid the ones you do not need. Thus, errors can be identified easily and where they occur.
  4. These human-readable comments can help non-programmers or beginners read and understand Python code.
  5. Comments can distinguish between the most important to none essential blocks of code or functions in your program. For example, you can insert comments on some functions to categorize them as important to the program. Thus, changing such functions would result in some problems with the program.
  6. Comments can provide a timeline/execution procedure of how the program executes, especially where multiple files are used across your program.
  7. Comments can be used to relay the thoughts of a programmer to the reader. For example, comments can be used to explain why some code is written in an unconventional way that deviates from what is commonly implemented by most programmers.
  8. Comments, especially multiline comments, can be used to temporarily disable a legacy version of a particular block of code as you try a new version.
  9. Comments can also provide meta descriptions to blocks of code, especially when there is team collaboration. Comments can be used to show who wrote the code, the date of updating the code, e.t.c.

Related Questions

Should Python comments be capitalized?

As a general guideline, Python comments should start with a capital letter and follow a sentence format. So, you should not capitalize all the characters of your Python comments.

As a general rule:

  1. Keep your comments short and to the point (and probably sweet)
  2. Make your comments appear as full sentences
  3. Minimize your comments
  4. If you start with an identifier, do not alter their case. For example, do not write My_function in your comment when the function identifier is my_function.

Do python comments have to be indented in Python?

Whether you indent or do not indent your Python, they will not result in any syntax errors in your Python program. Python ignores single-line or multiline comments. Thus, they are not executed when your program runs.

So, do not worry whether you have inserted an indent in your Python comments or not. As a recommendation, it is a good practice to insert indent in your multiline comments to achieve readability and make it easy to scan your code and comments.

Should comments be above or below the code?

To follow what other programmers do, you should insert your comments just above the code on which you want to comment. It makes more sense to prepare the reader for what is to come on the code implemented below the code.

Besides, as code is read from top to bottom, it makes more sense to put your comments at the top of your code.

Another thing that should make you put the code at the top of your code is to make it easy to find your comments by the future you and other programmers. It would cause more visual memory to look for comments at the bottom, scroll back up, and start checking your code.

Placing your comments above your code follows the de facto standard that outlines that comments should be:

  1. Placed before the code or code block it explains
  2. Placed on the same line with the code it describes

Do comments affect performance in Python?

Comments never affect the performance of your Python program because, in the first place,

  1. They are stripped off during code compilation
  2. They are ignored and never executed.

As Python programs are first compiled (turned in .pyc) and then interpreted, comments are removed. Thus, during the execution phase, there is no effect on performance that comments would have on your Python program. GeeksforGeeks explains it so well how Python code gets compiled and interpreted.

Although negligible, a gigantic amount of comments in your Python code may slow down the compilation process when comments are stripped from your program.

What is the shortcut to comment multiple lines in Python?

To comment multiple lines of Python code, follow these steps

Step 1: Highlight/Select part of the code or code block you want to comment

Highlight the Python code you want to comment

Step 2: Press shortcut/combination keys based on the editor/IDE or system you are using

In spyder, press CTRL + 1

In Visual Studio Code, highlight the code you want to comment, press CTRL + /

In Pycharm, highlight the code, press CTRL + SHIFT + /

In Jupyter Notebook, highlight the code to comment, press CTRL + /

That’s it for this article.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *