Python - Comments



A comment in a computer program is a piece of text that is meant to be an explanatory or descriptive annotation in the source code and is not to be considered by compiler/interpreter while generating machine language code. Ample use of comments in the source program makes it easier for everybody concerned to understand more about syntax, usage and logic of the algorithm etc. provided it has been commented nicely.

Python Comments

Python comments make code easier to understand and they are completely ignored by the interpreter, which means you can provide as many comments as you like in your program to make it more readable and explainatory.

Python supports two types of comments:

  • Single-line comments
  • Multi-line comments

Single Line Comments in Python

In a Python script, the symbol # marks the beginning of comment line. It is effective till the end of line in the editor. If # is the first character of line, then entire line will be assumed as a comment and interpreter will ignore it.

Example of Single Line Comments in Python

# This is a comment
print ("Hello World")

If # is used in the middle of a line, text before it is a valid Python expression, while text following it is treated as comment.

print ("How are you?") # This is also a comment but after a statement.

Commenting on Python Code Statement

Sometime there is a situation when you don't want a particular line of Python code to be executed, then you can simply comment it as below:

# This is a comment
# print ("How are you?")
print ("Hello World")

Multi Line Comment in Python

In Python, there is no provision to write multi-line comment, or a block comment. (As in C/C++, where multiple lines inside /* .. */ are treated as multi-line comment).

Each line should have the "#" symbol at the start to be marked as comment in Python and that's how you can create multi-line comments in Python. Many Python IDEs have shortcuts to mark a block of statements as comment.

Example of Multi Line Comments in Python

#
# This is a multi-line comment
#  which can span through multi-line.
#
print ("Hello World")

Multi Line Comment Using Triple Quotes

A triple quoted multi-line string is also treated as comment if it is not a docstring of a function or class.

'''
First line in the comment
Second line in the comment
Third line in the comment
'''
print ("Hello World")
Advertisements