Use this tutorial to learn how to write comments in Python for various situations.
Materials required: Latest version of Python (Python 3), an integrated development environment (IDE) of your choice (or terminal), and a stable internet connection.
Prerequisites/helpful expertise: Basic knowledge of Python and programming concepts
Using comments correctly makes your code easier to understand. They’re essential for collaborative projects, code documentation, testing, and debugging. By the end of this tutorial, you will be able to use Python comments strategically to write more readable code.
Term | Definition |
---|---|
Hashmark | In Python, a hashmark, hash character, or hashtag (#) tells the interpreter to ignore the rest of the line of code. |
Indentation | Indentation is the space at the beginning of each line of code. In Python, indentation indicates a new line of code. In other programming languages, it is used only for readability purposes. |
Source code | Source code is the human-readable instruction a coder writes to develop programs. |
Interpreter | An interpreter is a computer program that translates source code into machine code that the computer can read and execute. |
Newline | In Python, \n is used to create a new line. If inserted into a string, all characters after \n will be added to a new line. |
Comment out | Commenting out code describes using the hashmark to turn code into a comment so that Python will ignore it. |
Docstring | A Python docstring is a string literal used to document a specific class, module, method or function. |
To add a comment in Python, follow these four steps:
Example:
1 2 3 4 5
print(5 + 10) y = 20 * 5 print(y) # Hi, this is a comment print("This is a print statement")
As you can see from this code, the interpreter will run the first three lines, skip the comment, and run the last line. The output should look like this:
Why don’t I see comments when I run a program?
An inline comment exists on the same line as a statement. You can create an inline comment by adding the hash character to the end of the line you want to comment on. This format is ideal for comments that provide context for the code. Here’s what it looks like:
1 2
def price_adjust(price): return price * 0.13 #Price increase to adjust for inflation rate
It is recommended to use inline comments sparingly to keep your code readable. The bulleted list below contains a few tips for ensuring your comments are necessary and concise:
Unhelpful:
1 2 3
statetax = 1.0625 # Assigns the float 1.0625 to the variable 'statetax' citytax = 1.01 # Assigns the float 1.01 to the variable 'citytax' specialtax = 1.01 # Assigns the float 1.01 to the variable 'specialtax'
The comments in this code simply tells us what the code does, which is easy enough to figure out without the inline comments. Remember, focus on the why and the how, rather than the what.
Helpful:
1 2 3
statetax = 1.0625 # State sales tax rate is 6.25% through Jan. 1 citytax = 1.01 # City sales tax rate is 1% through Jan. 1 specialtax = 1.01 # Special sales tax rate is 1% through Jan. 1
In this case, it might not be immediately obvious what each variable represents, so the comments offer helfpul real-world context. The date in the comment also indicates when the code might need to be updated.
Python has no built-in methods for multiline commenting. However, you can still use the hash character to comment several single-line comments. Here’s an example:
1 2
# You can create a multiline comment # by adding the hash symbol to each line
How many multiline comments can I create?
In Python, a code block is defined as multiple lines of code grouped on the same indentation level. If you have a larger block of code to comment, you may consider using documentation strings (docstrings) rather than the block comment method above. Docstrings are the string literals appearing directly after the definition of a function. You can use them to associate documentation with classes, functions, modules, and methods, but you can also use them to comment out code.
To create a single-line docstring in Python, follow these three steps:
There should be no blank lines before or after a single-line docstring. You should also always use double quote characters for triple-quoted strings to align with the docstring convention in the Style Guide for Python Code.
Example:
1
''' This is a comment using string literals with triple quotes '''
Another way to create a multiline comment is to wrap it inside a set of triple quotes, similar to a multiline docstring. Technically, this is not a comment; it’s a string that isn’t assigned to any variable. This means that the interpreter will read the code but will not do anything with it. Here’s what the syntax should look like when you use this method:
Example:
1 2 3 4 5
''' This is a multiline comment using string literals with triple quotes '''
Although the docstring method does give you multiline comment functionality, remember that they are not technically comments. They are strings that are not assigned to any variable, allowing the program to ignore them at runtime. You can further compare and contrast Python comments and docstrings with the following chart:
Python comment | Python docstring |
---|---|
Used to leave notes about a segment of code | Used to document functions, classes, and modules |
Exists only in the source code | Will be embedded in code for some modules, functions, and classes |
Enables the programmer to provide additional information about the code | Enables the program to provide descriptions of modules, functions and classes |
Describes why and how, not what | Describes what, not how or why |
Can not be accessed with the built-in help function and doc attribute | Can be accessed with the built-in help function and doc attribute |
You can use Python comments to create reminders for yourself or leave helpful documentation for others. They provide users with a way to communicate logic, algorithms, and formulas in source code without affecting the program’s execution. In addition to documenting code, you can use Python comments for testing and debugging.
There are several ways to use Python comments for testing and debugging purposes:
Example:
1 2 3
a = 2 + 5 #b = 7 + "four" c = "eight" + "zero"
The second line (b = 7 + "four"
) will cause an error, but if we comment it out, our code will run properly. Commenting is a good way to test which line of your code may contain an error during debugging.
You can stay up to date on Python tips and releases by getting involved with the Python community. Subscribe to the free Python email newsletter or connect with peers by joining the Python programming Slack channel.
Take the next step in mastering the Python language by completing a Guided Project like Testing and Debugging Python. For a deeper exploration of the language that rewards your work with a certificate, consider an online course like the Python 3 Programming Specialization from the University of Michigan.
This content has been made available for informational purposes only. Learners are advised to conduct additional research to ensure that courses and other credentials pursued meet their personal, professional, and financial goals.