multiline comment python

How to Comment in Python

Often you may need to add comments to your python code or script in order to make it easy for others to understand and modify your code. Python supports several types of comments. In this article, we will learn the different ways to comment in python.

How to Comment in Python

Here are the different ways to comment in Python programming language.

1. Single Line Comment

The single line comment consists of hash(#) sign followed by a space. All the characters that follow single line comment, on the same line as the hash & space characters, will not be executed during run time. Here is an example of single line comment.

# here is a single comment

In the above code, only the second line is executed and not the first one.

You can the use the single line comment in different ways. Please note, you can use as many single line comments as you want and wherever you want. Just keep in mind that all characters after hash & space, on the same line, will not be executed

Inline comment

One of the most common ways to use single line comment is to add it inline at the end of code, explaining what it does. Here is an example.

print('Hello') # prints hello

In the above code block, python will print Hello and world but not the part after hash & space characters.

Comment Block

You can also use the single line comments to create a block, for more details. Here is an example.

# function to print hello world
# created on 10/11/2021
# by adam smith
def hello_world():
    print('hello world')

Also, you don’t need to follow indentation when using single line comments.

2. Multiline comments

If you have a large block of code that you want to comment, then you may want to use multiline comment, instead of adding hash & space at the beginning of all your lines.

Multiline comment consists of tripe quotes. They can be 3 single or double quotes back to back. But don’t use both at the same time. Here are two examples to give you an idea. All lines between triple quotes are ignored during execution.



test multiline

Don’t use single and double quotes as shown below. They will not be interpreted as comments but only as quotes.

wrong multiline comment


wrong comment

Please note, multiline comments need to follow proper indentation unlike single line comments, else you will get indentation error. Also if you multiline comment after any of the following, then python will interpret it as docstring

  • after function signature
  • after class definition
  • at the start of a module

In this article, we have learnt how to comment in python.

Also read:

Git Rename Local & Remote Branch
How to Create Remote Git Branch
How to Unstage Files in Git
How to Enable Bluetooth in Command Line
How to Add Repository in Ubuntu

Leave a Reply

Your email address will not be published.