Comment source code in python
Frequently you would be required to share your code with others for cross verification, suggestion, as an assignment, or further development. In the code, you can leave a message for other coders for the understanding of code. After a gap of time, if you revisit your code and read your long codes, even you may not be able to understand some portion of your code. It is therefore always desirable to leave some messages or comments for code readers by the programmers.
Let's take an example:
Below is the message for blog readers print(“please share this blog wit friends”) |
If you run this code, you will encounter an error
because the first line is not code, but is a message. The system tries to
interpret this message as code and thus is throwing an error. If we want to
instruct the Python interpreter to leave out this line while execution, we have
to comment on this line. This can be done in the following ways.
#Below is the message for blog readers print(“please share this blog wit friends”) |
Or |
print(“please share this blog wit friends”) #Below
is the message for blog readers |
The “#” when inserted before a line or word or codes, the matter written after “#” are not read by python for execution purposes. Thus the process of instructing python to exclude some portion of the code from execution is known as comments.
Multiline comment code in python
What if we want to comment on multiple lines? An
example is shown below:
#Below is the message for blog readers #Your positive feedback keeps us motivated #If you have thrilled by reading this blog,
consider donation:) print(“please share this blog with friends”) |
“””Below is the message for blog readers Your positive feedback keeps us motivated If you have thrilled by reading this blog,
consider donation:)””” print(“please share this blog with friends”) |
In case, you are required to comment on multiple lines, you can do the same by putting the “#” mark at the starting of each line. However, when there are multiple lines this becomes tedious and you can put three double quotes at the beginning and the end of multi-line comments like above
Shortcut for comment code in python
In pycharm, we have a shortcut for commenting
multiple lines. For commenting on multiple lines, select all the lines to be
commented on and press “CTL” and “/” keys. For un-commenting of these lines,
you can again press the shortcut keys.