- Python Comment Block
- Introduction to Python Comment Block
- Types of comments in Python
- Single-line comments
- Inline comments
- Multiline comments
- Using Multiple Hashtags (#)
- Python docstrings
- Single line docstrings
- Multi-line docstrings
- How to block a comment in Python?
- Table of contents
- Block comment in Python
- Using multiple single # line comments to add a block comment in Python
- Input:
- Output:
- Using triple-quoted string literals to create block comment in Python
- Input:
- Output:
- Closing thoughts
- Python Comments – Multiline Comments, Best Practices
- How to Write Comments in Python?
- Python Comments Examples
- 1. Comment for Variables
- 2. Comments for Functions
- 3. Comments for Class
- Python Comment Block or Multiline Comment
- Using Python Docstring as Multiline Comment
- Is it a good idea to use Docstring to specify long multiline comments?
- Python Multiline String as Multiline Comments
- Python Commenting Best Practices
- Python Comment Shortcut to Comment Out a Block
- Summary
- What’s Next?
- References:
Python Comment Block
Comments are a piece of text in a computer program that provides more information on the source code written. Like every other programming language, Python has three different types of comments: single-line comments, multiline comments, and documentation string to comment out block of code.
Introduction to Python Comment Block
Comments are used to explain the source code. Comments are mainly used for the following purposes.
- Improve Code readability
- Testing the code
- Explaining the code or Metadata of the project
- Prevent execution of specific code blocks
For example, let’s say you have written complex business logic, formulas, algorithms, etc. Then we need to document it using the comments that explain what the code does, thus improving the readability of the code in Python.
Python interpreter ignores the comments while executing the code and only interprets the code.
Types of comments in Python
- Single-line comments
- Multiline comments
- Documentation strings, aka docstrings
Let us look into details on how to use these comments in Python code with examples.
Single-line comments
Single-line comments, also called block comments, start with a hash sign (#) followed by a single space and a text string.
The hash (#) works with only a single line of code and not on multi-line code.
Let’s take an example to demonstrate single-line comments in Python.
# This is a single line comment example print("Hello World")
Inline comments
If you place the comment in the same line as a statement, you will have an inline comment.
Like single-line comments, inline comments also begin with a hash (#) sign and are followed by a space and the comment text.
Let’s take an example to demonstrate inline comments in Python.
print("Hello World") # This is a example of inline comment
Multiline comments
Usually, in other languages like Go, C, C#, Java, etc., we can write a multi-line comment as shown below.
/* This is a comment block which supports Multi-line code */
But in Python Multiline comments do not exist built-in like other programming languages.
Python may not have any built-in mechanism for commenting out multiple lines. However, there are different ways to achieve this in Python.
Using Multiple Hashtags (#)
We can use multiple hashtags to write multiline comments in Python. Each line that has a hash sign(#) is considered as a single-line comment.
# This is how we can acheive # Multi-line comments in Python print("Hello World")
Python docstrings
Documentation strings, also called docstrings, are the string literal denoted with triple quotes that occur as the first statement in a module, function, class, or method definition. Conventions for writing good documentation strings (a.k.a. “docstrings”) are immortalized in PEP 257.
Note: We can also use triple """
quotations to create docstrings.
Single line docstrings
Let’s take an example to demonstrate single line docstring.
def Add(a,b): '''Takes two number as input and returns sum of 2 numbers''' return a+b
Inside the triple quotation marks is the docstring of the function Add() as it appears right after its definition.
Multi-line docstrings
The multi-line docstring can span across multiple lines of code starts with triple quotes( «»» ) and ends with triple quotes ( «»» ).
We can use multiline docstring as multiline comments in Python to comment out block of code. The creator of Python, Guido Van Rossum, also recommended this and mentioned it on Twitter as a Pro-tip.
The following example shows you how to use multi-line docstrings. Make sure to indent the leading »’ appropriately to avoid an IndentationError
def Add(a,b): '''Takes two number as input Adds a and b Returns sum of a and b as output ''' return a+b print(Add(5,6))
Note: As long as the string is not assigned to any Python variable, Python will read the code but then ignore it, and you have made a multiline comment.
How to block a comment in Python?
Unlike other programming languages such as C, C++, and Java, Python does not support /*. */ for multi-line comments or block comments, there is no built-in mechanism for block comments in Python. We have different conventions and syntax for block comment in Python. Here you will read about adding block comments to your code.
Table of contents
- Understanding the concept
- Using multiple single # line comments
- Using triple-quoted string literals for block comments
- Closing thoughts
Block comment in Python
Comments are specially marked lines of text in the program that are not evaluated. There are usually two ways to comment in any programming language.
The first is known as a single-line comment because it only applies to a single line in the «source code»(the program) and the second type of comment is a Block comment, and it usually relates to a paragraph of text. A block comment has a start and an end sign, and the computer ignores everything in between.
Using multiple single # line comments to add a block comment in Python
The most common way to comment out a block of code in Python is using the # character. Any line of code starting with # in Python is treated as a comment and gets ignored by the compiler.
Since only a line of code after the # character is considered a comment, so it is great for single-line comments, so you can use it as many times as you want in a single code.
Input:
# This is block comment # Made using # character # Used multiple times print ("Block Comment")
Output:
Using triple-quoted string literals to create block comment in Python
In order to write a proper block comment in Python, we can use triple-quoted syntax with multi-line strings. These strings should not be confused with Docstrings (triple-quoted string literals appearing right after a function/class/module to create documentation). If we use it to comment out multiple lines of code in Python, that block of code will be ignored, and only the lines outside the docstring will run.
Despite the fact that triple quoted string literals do not generate code, they are handled as such and must be indented properly within blocks in order to function properly!
Input:
""" This is block comment Made using # character Used multiple times """ print ("Block Comment")
Output:
If you use 4 spaces (or a tab) for indentation, you will get an indentation error.
Closing thoughts
Since there’s no built-in support for multi-line comments in Python, we can use a triple-quoted multi-line string for creating block comments. Still, you should generally stick to using regular Python comments using a # character, even if you have to use it for multiple lines. This is because docstrings are for documentation, and not for commenting out code. One can learn about more Python concepts here.
Python Comments – Multiline Comments, Best Practices
Comments are an integral part of any program. Every programming language provides a way to add comments. Python commenting system is very easy. In this guide, we will learn about comments in Python. They provide useful information about the code to the developers.
How to Write Comments in Python?
- Python comments start with the # character and extend to the end of the line.
- We can start a comment from the start of the line, after some whitespaces or code.
- If the hash character is present in a string literal, it’s part of the string.
Python Comments Examples
We can add comments for variables, functions, and classes. They are used to provide the intended use of the part of the code. Let’s look at some examples of comments in Python.
1. Comment for Variables
name = "Pankaj" # employee name id = 100 # employee id data = "#123" # this is comment, data contains # and that is not part of the comment.
2. Comments for Functions
# This function adds the two numbers def add(x, y): return x+y
3. Comments for Class
# This class provides utility functions to work with Strings class StringUtils: def reverse(s): return ''.join(reversed(s))
Python Comment Block or Multiline Comment
Sometimes it’s not feasible to have the comment in a single line. In this case, we can create a comment block or split the comment into multiple lines. We have to prefix every line with the hash (#) to write a multiline comment.
# This class provides utility functions to work with Strings # 1. reverse(s): returns the reverse of the input string # 2. print(s): prints the string representation of the input object class StringUtils: def reverse(s): return ''.join(reversed(s)) def print(s): print(s)
Using Python Docstring as Multiline Comment
Python documentation strings (Docstring) are used to provide documentation for functions, classes, and modules. They are defined between a pair of triple double-quotes (“””). They must be defined just below the function or class declaration.
Let’s have a quick look at some examples of Python docstrings.
def foo(): """The foo() function needs to be implemented. Currently, this function does nothing.""" pass class Data: """ This class is used to hold Data objects information."""
We can access the docstring of an entity using __doc__ attribute.
print(foo.__doc__) print(Data.__doc__)
Is it a good idea to use Docstring to specify long multiline comments?
Python docstrings’ purpose is to provide documentation. Sometimes you will notice that it’s misused to provide long comments. However, it’s not the recommended approach. If you want the comment to spread into multiple lines, just prefix every line with the hash character.
Python Multiline String as Multiline Comments
We can also use multiline strings as multiline comments. According to this Guido’s tweet, they generate no code.
''' This function read employees data from the database emp_id: employee id, should be int returns employee object. ''' def read_emp_from_db(emp_id): i = int(emp_id) '''code to read emp data using the employee unique id number''' pass
However, it can lead to issues with indentation. It’s also confusing as to why a string is present in the code without any use. So, it’s better to stick to the regular multiline comments using hash characters.
Python Commenting Best Practices
- Always provide meaningful comments to specify the use of the entity.
- It’s better to break the long comment into multiple lines.
- Don’t be rude in the comments.
- Keep the comments to the point. Nobody wants to read a novel in the code comments.
- Avoid useless comments that don’t provide any useful information. Below are some examples of useless comments.
# count variable count = 10 # foo() function def foo(): pass
- Sometimes comments are unnecessary. Having the proper name of the entity itself is good enough. Let’s look at an example of this scenario.
# This function add two numbers def foo(x, y): return x + y # Better to have function defined as below. There is no use of comments. def add_two_numbers(x, y): return x + y
- It’s always a good idea to have a commenting system in place. When working with many team members and multiple projects in an organization, using a commenting policy is recommended. For example, you can define a commenting policy like this:
# - # Data Object - stores the Data fetched from the database data_obj = Data() # # # # # This function adds all the elements in the sequence or iterable # numbers: sequence or iterable, all the elements must be numbers # Returns the sum of all the numbers in the sequence or iterable # Throws ArithmeticError if any of the element is not a number def add_numbers(numbers): sum_numbers = 0 for num in numbers: sum_numbers += num return sum_numbers
Python Comment Shortcut to Comment Out a Block
If you are working with Python IDE or Jupyter Notebook, you can use a shortcut to comment out a block of the code.
- macOS Comment Shortcut – Select the lines you want to comment and press Command+/ and it will automatically add # at the start of each line to turn them into a comment block. If it’s a blank line, it will add # at the start of the line and you can write the comment.
- Windows and Linux Comment Shortcut – Use Ctrl+/ as the shortcut to turn a code block into a comment.
Summary
- Python commenting system is simple and always starts with #.
- Python docstring is used for documentation. You should not misuse it for multiline comments.
- Start every line with the hash character for multiline comments.
- Follow the best practices for adding comments to the program.
- Having a commenting policy in place is always a good idea when working with many team members.
What’s Next?
We referenced a lot of topics in this tutorial, you should read the following tutorials to get a further understanding of them.