Python Comments

In computer programming, comments are hints that we use to make our code more understandable.

Comments are completely ignored by the interpreter. They are meant for fellow programmers. For example,

# declare and initialize two variables
num1 = 6
num2 = 9

# print the output
print('This is output')

Here, we have used the following comments,

  • declare and initialize two variables
  • print the output

Types of Comments in Python

In Python, there are two types of comments:

  • single-line comment
  • multi-line comment

Single-line Comment in Python

A single-line comment starts and ends in the same line. We use the # symbol to write a single-line comment. For example,

# create a variable
name = 'Eric Cartman'

# print the value
print(name)

Output

Eric Cartman

Here, we have created two single-line comments:

  1. # create a variable
  2. # print the value

We can also use the single-line comment along with the code.

name = 'Eric Cartman' # name is a string

Here, code before # are executed and code after # are ignored by the interpreter.


Multi-line Comment in Python

Python doesn't offer a separate way to write multiline comments. However, there are other ways to get around this issue.

We can use # at the beginning of each line of comment on multiple lines. For example,

# This is a long comment
# and it extends
# to multiple lines

Here, each line is treated as a single comment, and all of them are ignored.

Another way of doing this is to use triple quotes, either ''' or """.

These triple quotes are generally used for multi-line strings. But if we do not assign it to any variable or function, we can use it as a comment.

The interpreter ignores the string that is not assigned to any variable or function.

Let's see an example,

''' This is also a
perfect example of
multi-line comments '''

Here, the multiline string isn't assigned to any variable, so it is ignored by the interpreter. Even though it is not technically a multiline comment, it can be used as one.


Use of Python Comment

1. Make Code Easier to Understand

If we write comments in our code, it will be easier for future reference.

Also, it will be easier for other developers to understand the code.

2. Using Comments for Debugging

If we get an error while running the program, we can comment the line of code that causes the error instead of removing it. For example,

print('Python')

# print('Error Line )

print('Django')

Here, print('Error Line) was causing an error so we have changed it to a comment. Now, the program runs without any errors.

This is how comments can be a valuable debugging tool.

Note: Always use comments to explain why we did something rather than how we did something. Comments shouldn't be a substitute to explain poorly written code.

Video: Comments in Python