Comments in Python Programming
In this lesson, we will understand what comments are and how it works in Python programming with the help of some examples.
What are Comments
In Python program Comments are portions of the code ignored by the interpreter which allow the user to make simple notes in the relevant areas of the source code.
Comments in Python programming are used to provide information about lines of code. It is widely used for documenting code.
Let's look at some examples to understand this better.
# Printing Hello World on the screen.
print("Hello World") # Now we are going to print Hello World.
Hello World
In the first line, we used a single-line comment to explain what we are going to do in the next line. You can also write a comment at the end of a statement, as shown in the second line.
# In this program we will learn how
# to print Hello World on the screen
print("Hello World")
# print("\nThis is a Python tutorial")
Hello World
From the 1st line to the 2nd line, we used multi-line comments to explain what the program is about. You can also comment on any statement that you don't want to execute but want to keep for future reference, as shown in the 4th line.
Python does not have a specific syntax for multi-line comments. To comment on multiple lines, we must place the # symbol at the beginning of each line, as shown in the example.
However, a common trick is to use a multi-line string for comments. The Python interpreter will not execute the multi-line string unless it is assigned to a variable. Let's look at an example to understand this better.
""" In this program we will learn how
to print Hello World on the screen """
print("Hello World")
Here you can see that we have used multi-line string to implement it as a multi-line comment. We can use either triple single quotes (''') or triple double quotes (""") to define a multi-line string. In between the opening and closing triple quotes, we will implement our multi-line comments as shown in the example above.