How to Use a Python Comment: Block, Inline, and Multiline

Written by Coursera • Updated on

Use this tutorial to learn how to write comments in Python for various situations.

[Featured image] A coder sits in an office using python comments to write readable code.

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.

Glossary

TermDefinition
HashmarkIn Python, a hashmark, hash character, or hashtag (#) tells the interpreter to ignore the rest of the line of code.
IndentationIndentation 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 codeSource code is the human-readable instruction a coder writes to develop programs.
InterpreterAn interpreter is a computer program that translates source code into machine code that the computer can read and execute.
NewlineIn 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 outCommenting 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.

How to comment in Python

To add a comment in Python, follow these four steps:

  1. Make sure your comment begins at the same indent level as the code it's about.
  2. Begin with the hashtag (#) and a space. The hash character tells the interpreter to ignore the rest of the line of code.
  3. Write your comment.
  4. Close your comment with a newline. Python will start reading your code again after the line containing the comment ends.

Example:

PYTHON
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: Screen Shot 2022-11-04 at 4.07.19 PM

Why don’t I see comments when I run a program?

Comments are for users’ eyes only. They exist solely in the source code because the computer does not need to read or execute them. Remember, comments are for humans, not for computers.

Inline commenting in Python

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:

PYTHON
1
2
def price_adjust(price):
    return price * 0.13 #Price increase to adjust for inflation rate

Guidelines for inline Python comments

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:

  • Avoid using comments to explain what your code does. If your code is too complex for other programmers to understand, consider rewriting it for clarity rather than adding comments to explain it.
  • Focus on the why and the how.
  • Make sure you’re not reiterating something that your code already conveys on its own. Comments should never echo your code.

Examples of helpful vs. unhelpful comments

Unhelpful:

PYTHON
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:

PYTHON
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.

How to comment out multiple lines in Python

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:

PYTHON
1
2
# You can create a multiline comment
# by adding the hash symbol to each line

How many multiline comments can I create?

There is no limit to the number of comments you can add because Python treats every line beginning with a hashtag like a comment.

How to comment out a block of code in Python

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.

One-line docstrings

To create a single-line docstring in Python, follow these three steps:

  1. Make sure your docstring begins at the same indentation level as the scope.
  2. Use a triple quote to start the string, followed by a phrase beginning with a capital letter and ending with a period.
  3. Close the string with triple quotes.

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:

PYTHON
1
''' This is a comment using string literals with triple quotes '''

Multiline docstrings

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:

PYTHON
1
2
3
4
5
'''
This is a multiline
comment using string literals
with triple quotes
'''

What is the difference between comments and docstrings in Python?

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 commentPython docstring
Used to leave notes about a segment of codeUsed to document functions, classes, and modules
Exists only in the source codeWill be embedded in code for some modules, functions, and classes
Enables the programmer to provide additional information about the codeEnables the program to provide descriptions of modules, functions and classes
Describes why and how, not whatDescribes what, not how or why
Can not be accessed with the built-in help function and doc attributeCan be accessed with the built-in help function and doc attribute

Why comment in Python?

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.

Using Python comments for testing

There are several ways to use Python comments for testing and debugging purposes:

  • Commenting out new code to ensure smooth implementation
  • Trying out various programming methods by commenting out code and running each one to compare results
  • Pinpointing the source of an error by commenting out and running parts of a program systematically

Example:

PYTHON
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.

Key takeaways

  • Comments and docstrings should be made at the same indentation level as the code they’re about.
  • Comments begin with a # and a space.
  • Docstrings begin and end with triple quotes.
  • Python has no built-in function for multiline comments, but you can use several lines beginning with hash characters or docstrings.
  • Comments should be about the why and the how.
  • Docstrings should be about the what.

Resources

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.

Continue building your Python expertise with Coursera.

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.


Written by Coursera • Updated on

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.

Learn without limits