Code Comments in Python

In this article, we would discuss how to write single-line and multi-line comments in Python. Code commenting is practice of writing short description of the instruction set we write. It makes the code easier to understand.

Consider a scenario, wherein we wrote thousand lines of code. And, then we moved to the other project. Now, if the code isn’t properly commented then, it would be cumbersome to not only us but also to other developers who may try to modify the code for numerous reasons.

If we just explain the purpose of a particular line or a block of code then, it obviously makes this easier for everyone to understand the code.

Next, we will understand the concept with the help of Hello World! example.

There are two ways to comment our Python code

  1. Single-line comments and,
  2. Multi-line comments.

Code Comments in Python

I. Single-line comments: These are preceded by # (hash). In addition to, we can also use them as end-of-line comments.

For instance,

# This will print "Hello World!"
print("Hello World!")

or, for end-of-line comments

print("Hello World!") #This will print "Hello World!"

For single-line comments or end-of-line comments, the compiler simply ignores anything beyond #. Note: This will work only for a single line.

II. Multi-line comments: These comments are spread over multiple lines. They start and end with triple quotes (“””).

For instance,

"""This will
print
Hello World!"""

print("Hello World!")

In addition to, we can also use # in the beginning of each line.

# This will
# print
# "Hello World!"

print("Hello World!")

The utility of using triple quotes (“””) or hash (#) is different. So, use them as per your requirements.

In conclusion, we have discussed how to Code Comments in Python.

Additional Info – 

We would like to add here that, it is not necessary to have only single-line comments or multi-line comments in our code. We can use both types of comments inside our code. Apart from that, we recommend using Code comments always inside our code for above mentioned reasons. Code commenting helps us to know the purpose or intention behind writing the code.