Python
Comments
Python
Comment is an essential tool for the programmers. Comments are generally used
to explain the code. We can easily understand the code if it has a proper
explanation. A good programmer must use the comments because in the future
anyone wants to modify the code as well as implement the new module; then, it
can be done easily.
In
the other programming language such as C++, It provides the // for single-lined
comment and /*.... */ for multiple-lined comment, but Python provides the
single-lined Python comment. To apply the comment in the code we use the
hash(#) at the beginning of the statement or code.
Let's
understand the following example.
1.
# This is the print statement
2.
print("Hello Python")
Here
we have written comment over the print statement using the hash(#). It will not
affect our print statement.
Multiline Python Comment
We
must use the hash(#) at the beginning of every line of code to apply the
multiline Python comment. Consider the following example.
1.
# First line of the comment
2.
# Second line of the comment
3.
# Third line of the comment
Example:
1.
# Variable a holds value 5
2.
# Variable b holds value 10
3.
# Variable c holds sum of a and b
4.
# Print the result
5. a = 5
6. b = 10
7. c = a+b
8.
print("The sum is:", c)
Output:
The sum is: 15
The
above code is very readable even the absolute beginners can under that what is
happening in each line of the code. This is the advantage of using comments in
code.
We
can also use the triple quotes ('''''') for multiline comment. The triple
quotes are also used to string formatting. Consider the following example.
Docstrings Python Comment
The docstring comment is mostly used in the module, function, class or method.
It is a documentation Python string. We will explain the class/method in
further tutorials.
Example:
1.
def intro():
2. """
3.
This function prints Hello Joseph
4.
"""
5. print("Hi Joseph")
6. intro()
Output:
Hello Joseph
We
can check a function's docstring by using the __doc__ attribute.
Generally, four whitespaces are used
as the indentation. The amount of indentation depends on user, but it must be
consistent throughout that block.
1.
def intro():
2. """
3.
This function prints Hello Joseph
4.
"""
5. print("Hello Joseph")
6. intro.__doc__
Output:
Output:'\n This function prints Hello Joseph\n '
Python
indentation
Python
indentation uses to define the block of the code. The other programming
languages such as C, C++, and Java use curly braces {}, whereas Python uses an
indentation. Whitespaces are used as indentation in Python.
0 Comments