Python Comments

Comments are hints that we add to our code to make it easier to understand.

When executing code, Python's interpreter ignores comments.

For example, we have a program to print a text entered by the user.

name = input("Enter your name:")
print(name)

To make this program more readable, we can add comments like:

# Program to take the user's name

name = input('Enter your name')
print(name) 

Here, the line starting with # is a comment. The Python compiler ignores everything after the # symbol.

Now, let's understand the different types of comments in Python.


Single-line Comment

We use the hash(#) symbol to write a single-line comment. For example,

# declare a variable
name = 'John'

# print name
print(name)    # John

In the above example, we have used three single-line comments:

  • # declare a variable
  • # print name
  • # John

We can also use single-line comments alongside the code:

print(name)    # John

Note: Remember the keyboard shortcut to apply comments. In most text editors, it's Ctrl + / if you are on Windows & Cmd + / if you are on a Mac.


Multiline Comments

Python doesn't have dedicated multi-line comment syntax like some other programming languages like C++ and Java.

However, we can achieve the same effect by using the hash (#) symbol at the beginning of each line.

Let's look at an example.

# print(1)
# print(2)
# print(3)

We can also use multiline strings as comments like:

'''This program takes an input from the user
and prints it'''

name = input('Enter your name: ')
print(name)

Output

Enter your name: John
John

We can see that these unassigned multiline strings are ignored.


Prevent Executing Code Using Comments

Comments are valuable when debugging code.

If we encounter an error while running a program, instead of removing code segments, we can comment them out to prevent execution.

For example,

number1 = 10
number2 = 15

sum = number1 + number2

print('The sum is:', sum)
print('The product is:', product)

Here, the code throws an error because we have not defined a product variable.

We can comment out the code that's causing the error.

For example,

number1 = 10
number2 = 15

sum = number1 + number2

print('The sum is:', sum)
# print('The product is:', product)

Output

The sum is 25

Now, the code runs without any errors.

Here, we have resolved the error by commenting out the code related to the product.

If we need to calculate the product in the near future, we can uncomment it.


Why Use Comments?

We should use comments for the following reasons:

  • Comments make our code readable for future reference.
  • Comments are used for debugging purposes.
  • We can use comments for code collaboration as it helps peer developers to understand our code.

Also Read:

Video: Comments in Python

Did you find this article helpful?