Python Comments – Single and Multi line

Python Comments

Python Comments are used to explain the code functionality and make it more readable to another developer. This is very important for the maintenance of the code, or when you are part of a bigger team.

Most developers complain that they do not understand the code they have written a month earlier. So, ever for personnel projects, writing comments help you in the long run.

How to write Comments?

# symbol is used to write single line comments in Python. Anything that is preceded after # till the end of that line, is a comment.

You can write any text in the comment. You can even comment out part of your code, that would not want to run.

Comments will be not be considered for execution by Python Interpreter. Therefore, comments are only for developer understanding purpose and the Python completely ignores them while execution.

Example – Python Comment

Following is a simple example to write single line comment in Python.

#this is a comment
print("Welcome to pythonexamples.org")
Run this program

The first line starting with # is a single line comment.

Example – Comment at the end of statement

You can also write comment after code in that same line. The definition still holds. Anything written after # in that line is considered comment.

print("Welcome to pythonexamples.org") #this is a comment
Run this program

Example – Comment Code

And you can comment code as well, to prevent from execution.

#print("Hello World")
print("Welcome to pythonexamples.org")
Run this program

The first print statement is not executed, since Python interprets the line as a comment.

Python Multi-line Comments

You can write multi-line comments. There is no another symbol or arrangement to write multi-line comments in Python, but we can use a hack.

Example – Multi-line Comments using #

You can write multi-line comments using # as shown below.

#this is a comment
#this is another comment
#one more comment
print("Welcome to pythonexamples.org")
Run this program

You can also write a multiple line string, without assigning it to any variable. It does not affect the program output, and therefore can be considered as a comment. An example for multi-line comment using string hack is given below.

'''
this is 
multi-line string and servers as a comment
'''
print("Welcome to pythonexamples.org")
Run this program

Summary

In this Python Examples tutorial, we have learned how to write single line and multi line comments in Python programming language. # is used to write comments in Python. Multi line string literal can be hacked to represent a comment.