In the previous tutorial you learnt to write your first Python program. Now, let's learn about Python comments.
In Python, parts of code beginning with #
are called comments. For example,
# print a number
print(25)
Here, # print a number
is a comment. This line is completely ignored by the computer.
Comments are hints that we add to our code to make it easier to understand.
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 such as: 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 is an example
of multiline comment'''
print("Hello World")
Output
Hello World
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.
Next, we will learn about Python variables.