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.
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.
Example:
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:
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.Output:
Output: '\n This function prints Hello Joseph\n '
Note: The docstring must be the first thing in the function; otherwise, Python interpreter cannot get the docstring.
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.
Indentation uses at the beginning of the code and ends with the unintended line. That same line indentation defines the block of the code (body of a function, loop, etc.)
Generally, four whitespaces are used as the indentation. The amount of indentation depends on user, but it must be consistent throughout that block.
To indicate a block of code we indented each line of the block by the same whitespaces.
Consider the following example.
Output:
Enter the number: 10 Even Number Task Complete
The above code, if and else are two separate code blocks. Both code blocks are indented four spaces. The print("Task Complete") statement is not indented four whitespaces and it is out of the if-else block.
If the indentation is not used properly, then that will result in IndentationError.
0 comments:
Post a Comment
Thanks