People create notes and reminders for themselves all the time. When you need to buy groceries, you look through your cabinets, determine what you need, and write it down on a list. When you get to the store, you review your list to remember what you need.
Using notes comes in handy for all sorts of needs, such as tracking the course of a conversation between business partners or remembering the essential points of a lecture. Humans need notes to jog their memories.
Comments in source code are just another form of note. You add them to the code so that you can remember what task the code performs later.
Computers need a special way to determine that the text you’re writing is a comment, NOT code to execute. Python provides two methods of defining text as a comment and not as code. The first method is the single-line comment. It uses the number sign #, like this:
# This is a comment print("Hello from Python!") #This is also a comment.
A single-line comment can appear on a line by itself or it can appear after executable code. It appears on only one line. You typically use a single-line comment for short descriptive text, such as an explanation of a particular bit of code.
When you need to create a longer comment, you use a multiline comment. A multiline comment both starts and ends with three double quotes (“””), like this:
""" Application: Adding Python Comments.py Written by: Jimmy Jim-bose Purpose: Shows how to use comments in Python. """
Everything between the two sets of triple-double quotes is considered a comment. You typically use multiline comments for longer explanations of who created an application, why it was created, and what tasks it performs. Of course, there aren’t any hard rules on precisely how you use comments. The main goal is to tell the computer precisely what is and isn’t a comment so that we don’t get any errors.
Using comments to leave yourself reminders
You might write a piece of code today and then not look at it for a long time. You need notes to jog your memory so that you remember what task the code performs and why you wrote it. In fact, here are some common reasons to use comments in your code:
- Reminding yourself of what the code does and why you wrote it
- Telling others how to maintain your code
- Making your code accessible to other developers
- Listing ideas for future updates
- Providing a list of documentation sources you used to write the code
- Maintaining a list of improvements you’ve made
Using comments to keep code from executing
Developers/programmers also sometimes use the commenting feature to keep lines of code from executing (referred to as commenting out). You might need to do this in order to determine whether a line of code is causing your application to fail.