Comments are very important in any programming language. Primarily they can be used to describe parts your code which can be very useful when someone else looks through your code. It can also be a good reminder for yourself especially when come back to your code after a break.
It is a good skill to determine how long and precise your comments are. You shouldn’t comment every single line of your code. The code itself should be written clearly and easy to read. It is recommended to comment blocks of code or add information that can’t be easily expressed by code.
Here are a few examples of different styles of comments.
The single-line comment:
Notice how running the code given above doesn’t show any output. This is because the print statement has been commented out.
Comments add readability to your code.
Let’s say that you’re working on a big product in a corporate. You write code for a small module assigned to you and afterward get busy working on other areas. After a couple of months, you need to revisit your code to make changes. This is where comments are going to help you out. You might have forgotten how your module integrates with other modules or why your code is doing what it’s doing. But if you’d added lots of comments everywhere then it’ll make it a lot easier for you to understand the code.
Writing comments will also help other developers to understand your code.
Block-comments:
There’s another way people write comments. Using triple-quotes.
1 2 3 4 | Output: This is also a string Will "Long-Legged" Mackie tip-toed quietly through the woods. The dry leaves made a crispy sound as he tip-toed over them gripping his cutlas, ready for action. |
Technically, what we created in the previous example weren’t really comments. They were strings. Multi-line strings!
If you simply create a string but don’t perform any action on it then Python will not fail your program for it. Instead, Python will just ignore that string and move on with the program execution. Hence, these multi-line strings are also used as comments.
That said, the recommended way to create comments is by using the # symbols.
It is a good practice to sprinkle comments throughout your code. It makes your code more readable, not only for others but also for yourself.
You will come across lots of comments throughout the course and you’ll learn to appreciate them as you go along.