One key skill in writing code is the ability to use comments. Comments are usually used to leave notes about the function of the code. However, they can also be used to disable parts of the code.
This guide will show you how to use comments in Python effectively.
- A working Python programming environment
- The ability to create and edit Python files
Python Comment Basics
To mark a line as a comment, start the line with a hash sign and a space:
# This is a sample comment.
Using the hash sign to start the line tells the system to ignore everything on that line. You can still see it when you edit the file. When the application runs, it pretends like those lines don’t exist.
For example, in the Hello World program below:
# Display the text “Hello, World!” on the screen. print(“Hello, World!”)
The system will only run the code on the second line. The first line explains what the second line of code is supposed to do.
You can set any line as a comment, and use as many as you’d like. If your code has different blocks, you can use a comment to explain each one:
# Define a variable flowers as a list of strings. flowers = [‘rose’, ‘carnation’, ‘daisy’, ‘marigold’, ‘tulip’, ‘sunflower’] # Create a for loop to iterate through flowers list, and displays each string item. for flower in flowers: print(flower)
To mark a series of lines as a comment, add a hash sign to the beginning of each line:
# This is a comment # that runs on to # multiple lines.
Some text or code editors for programming (like Notepad++ or Atom) will allow you to highlight the text, then mouse-click to mark the block as a comment. These tools can save you time commenting out each line.
In general, you should use the hash sign for each line to mark it as a comment. This is the recommended and approved method. However, you may need a quick way to comment out a whole section. Use a triple-quote mark to achieve a similar function as a comment:
def addition_test(a, b): result = a + b “”” This is a block of commented lines. They aren’t parsed and interpreted by the compiler. “”” return result
Note: It is important that you correctly indent the triple-quote mark. If you don’t, you will see a syntax error.
This method doesn’t create a true comment. Instead, it creates a text constant with no function. As long as you don’t add anything that accesses that string of text, it will work the same as a regular comment.
The triple-quotation mark can be tricky, because in some circumstances it creates a docstring. If you use a triple-quote following:
- A function signature
- A class definition
- At the start of a module
…Python will read it as a dosctring. Docstrings let you put human-readable text into the project. This is usually used to create documentation that’s part of the application and can be accessed at runtime.
This is where you comment on the same line as a piece of code. The best time to use this is when you’re explaining a complicated operation. Use an inline comment to point out the exact spot you want to clarify.
Use the standard hash sign to signify an inline comment:
function set variable run command run additional command # Tricky part: The program breaks if this line is removed.
Inline comments can be used to add context for people who are reading the code. For example, you might explain the purpose of a variable, or leave a note about the type of variable created. It can also be helpful to explain why a particular command is used, as in the example above.
Commenting Out Code for Testing
Because comments render text invisible to the parser, you can use them to disable commands. This lets you test segments of your code with and without new additions.
For example, look at this simple dice rolling program:
import random min = 1 max = 6 roll_again = "yes" while roll_again == "yes" or roll_again == "y": print "Rolling the dice..." print "The values are...." print random.randint(min, max) print random.randint(min, max) # Add two random numbers together for a sum # while roll_again == “yes” or roll_again == “y”: # print ”Rolling the dice…” # print “You rolled a “ # print random.randint(min,max) + random.randint(min, max) roll_again = raw_input("Roll the dice again?")
The section that’s commented out is unused. Remove the hash sign to enable the code to test it.
Commenting Best Practices in Python
- Comment at the same indentation as the code you’re referring to. This makes it easier to see what you’re referring to.
- Update your comments when you update your code. Incorrect comments are worse than no comments.
- Use complete sentences. Capitalize appropriate words, unless you’re referring to an identifier (like a variable). Never change the case of an identifier.
- Block comments should be written out in complete sentences, with periods. Aim for 80 words per line or less.
- If you have multiple sentences in a comment, use a double-space between sentences.
- Write comments in English.
- For a block comment with multiple paragraphs, add a blank line between paragraphs with a single comment tag preceding a blank line.
- For inline comments, leave at least two spaces between the code and the comment. Use inline comments sparingly, and avoid using them to state the obvious.
You should now understand how (and why) to make comments in the Python language.