Python is a language that is known for its simplicity but sometimes the code becomes too long that it becomes necessary to use obvious names and by defining functions separately.
In addition, you can improve the readability of your code by using Python comments.
When to add comments
“Why are comments in coding even a thing?” you may ask and the answer is that python comments play an important role in explaining the code. Let’s have a look why comments are so important –
- Improves readability of the Python Code – Suppose, you are working on a project X which has lots of code but you missed to add any comments to any of your code changes. Now, you are asked to work for Project Y for 6 months. If your project manager ask you to start working on Project X again, it will be difficult for you to start on Project X quickly because you have to read the code changes again. If you would have added comments earlier, it was easy for you to understand the code faster.
- Like a Help guide to peers – If you provide comments for the important information of your code, it helps your peers(Co-workers) to understand your code faster.
- Debug and Test – To check if a particular code is causing an issue, you can comment the suspected code and run the remaining program to verify if the commented code is causing any issue.
How to write comment in python
You can comment a Single line or multiple lines of code so there are 2 types of comments-
- Single Line Comment
- Multi Line Comment
1. Single line comment in python
To comment a single line in Python, you can write a comment by simply putting the # symbol at the start of the text.
Python will ignore all the text that comes after the # symbol. The symbol is called as octothorpe or Hash symbol.
As you can see, the text after # is ignored by the Interpreter when the code was being executed.
2. Multi line comment in python
Python does not support multi line comments like Java, PHP or some other language. However, if you have multiple lines of comments, you can comment each line with the hash symbol (#). This is the recommended way to comment in Python.
For Example –
The alternate way to add multiple Line comments is by using the triple quoted strings like this –
This is basically a string that is not assigned to any variable. Therefore, I do not recommend using strings as comments.
- Use the comments only to explain the important block of code.
- Do not overuse comments else it will make the python code look ugly.
- In addition, avoid using comments to explain the simple codes or self explanatory codes.