How to Write Comments in Your Python Code Files
Writing comments in your Python code files is a good thing because you can communicate messages to your future self in the program text. Let’s take a look at an example code file.
""This is just a test file"" print('Hello World! from the editor')
The first line here is called a comment. It looks like string literals because that’s what it is. When Python sees a string literal in a file it ignores it! In this case, you’re telling yourself that this file is just a test file, so you shouldn’t be too bummed if you mess up.
You have a lot of good reasons to write comments in your code:
As an explanation. Whenever you create a new Python file, write a short explanation of what the code’s supposed to do. Don’t repeat what the code is doing. Summarize what the code is for. What do you want to achieve? So, in the code a = a+1 # adding 1 to a the comment is pointless because any fool can see that the code is adding 1 to a. You’d generally not include a comment here unless there was a reason that is not clear from the code. For example: a = a+1 # Changing a causes the data to be refreshed in the next code block.
As a memory aid. When you’re first writing your code you’re very close to it. You’re familiar with it. You understand why you’ve put what you’ve put where and why. As time goes by, you will forget why you put that piece of code somewhere. It’s a lot easier to read a description than work it out later.
As a means of communication. When you give your code to someone else, an English explanation of what the code does is even more important. Comments allow you to collaborate (work together) better with others. If you want to work as part of a programming team, you’d better have good comments in your code.
As a debugging aid. If there’s a problem with your code, someone will need to go in and fix it, and it may not be you. Again, having an English explanation of what’s going on is a big help.
Because it’s good for you. Like vegetables, only tastier.