What is comments in Python ?
# program to add two numbers a = 10 b = 5 c = a + b print("Sum= ", c)
The first line of the program starts with the # symbol. This is called comment in Python. A comment is used to describe the features of a program. When we write big programs sometime we don’t remember why we did certain. Writing comments helps us and others to understand our program. It increases the readability and understandability of our program.
What are types of comments in Python ?
There are two types of comments in Python –
- Single Line Comments
- Multi-Line Comments
1 . Single Line Comments –
The single line comments starts with the hash symbol ( # ) and are useful to mention that the entire line till the end should be treated as comments.
For example –
# program to add two numbers a = 10 # store 10 into variable a b = 5 # store 5 into variable b c = a + b # add both the numbers print("Sum= ", c) # print the sum
Here, the first line starts with a hash symbol so the entire line is treated as a comment. In the second line a = 10 is a statement. After this statement , # symbol starts the comment describing what this line is doing. The part of this line starting from # symbol to the end is treated as a comment.
Comments are non-executable statements. They are written for understanding the programs for the humans and not for the compilers. They are non-executable.
2 . Multi-Line comments –
Sometimes the comment that we are writing does not finished in one line. We might need multiple lines to describe the program. In that case we use multi-line comments. One tedious way to do is that writing hash symbol before the beginning of every comment line.
# This is a program to train a linear regression # model in scikit-learn. The goal is to predict # the housing prices.
Instead of starting every line with # symbol, we can write the previous code inside “”” (triple double quotes) or ”’ (triple single quotes) in the beginning an end of the block of code as shown below.
""" This is a program to train a linear regression model in scikit-learn. The goal is to predict the housing prices. """
or like this
''' This is a program to train a linear regression model in scikit-learn. The goal is to predict the housing prices. '''
The triple double quotes ( “”” ) or triple single quotes ( ”’ ) are called multi line comments in Python. They are used to enclose a block of lines as comments.