How to comment in python
How to comment in python
Commenting Python Code
Programming reflects your way of thinking in order to describe the single steps that you took to solve a problem using a computer. Commenting your code helps explain your thought process, and helps you and others to understand later on the intention of your code. This allows you to more easily find errors, to fix them, to improve the code later on, and to reuse it in other applications as well.
Good vs Bad Comments
As important as comments are, it’s still possible to write bad comments. They should always be short, straight to the point, and add informative value.
For example, this is a rather useless comment:
The next example shows a more helpful comment, instead, and goes along with giving variables obvious names:
There are an infinite number of other scenarios that warrant comments. This is just one example. A good rule of thumb would be to add comments for any line of code (like a list comprehension) or section of code whose purpose isn’t obvious. This is very subjective, and is actually a skill that needs to be learned.
Types of Comments
In the following sections I’ll describe each type of comment.
Single-Line Comments
Such a comment starts with a hash character ( # ), and is followed by text that contains further explanations.
You can also write a comment next to a code statement. The next example shows that:
The Style Guide for Python Code (PEP8) recommends less than 79 characters per line. In practice, 70 or 72 characters per line are easier to read, and thus is recommended. If your comment is approaching or exceeding this length then you will want to spread it out over multiple lines.
Multi-Line Comments
As already mentioned above, an entire comment block is also understood by Python. These comments serve as in-line documentation for others reading your code, and explain things in more detail, usually.
Technically Python doesn’t have explicit support for multi-line comments, so the following options are considered a workaround by some, but still work for the purpose of multi-line comments.
Version 1 combines single-line comments as follows:
Version 2 is simpler than version 1. It’s originally intended to be used for creating documentation (see more about this below), but it can also be used for multi-line comments.
Note that the latter version needs to be enclosed in special quotation marks ( «»» ) to work, and not hash characters.
Common Practice
It is quite common to start a Python file with a few lines of comments. These lines state information regarding the project, the purpose of the file, the programmer who developed it or has worked on it, and the software license that is used for the code.
This snippet is taken from one of the examples I use for training purposes. The comment starts with the description, and is followed by the copyright notice with my name, and the year of publication of the code. Below you will see that the code is licensed under GNU Public License (GPL). In order to contact me my email address is added there too.
Docstring Comments
Python has a built-in concept called docstrings, which is a great way to associate documentation you’ve written with Python modules, functions, classes, and methods. A docstring is added as a comment right below the function, module, or object head, and describes what the function, module, or object does. It is expected to follow these rules:
Free eBook: Git Essentials
Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!
A docstring is either a single line, or a multi-line comment. In the latter case, the first line is a short description, and after the first line an empty line follows.
Begin the docstring with a capital letter, and end it with a period.
This is a basic example of what it looks like:
In the Python interactive help system, the docstring is then made available via the __doc__ attribute.
There is a number of tools that auto-generate documentation from docstrings, such as Doxygen, PyDoc, pdoc, and the autodoc extension for Sphinx. We will explain to you how to work with them in a follow-up article.
Conclusion
Writing proper comments in your Python code is not that complicated, and you just need the power of endurance. It helps all of us that are trying to understand your code, including yourself for when you revisit your code at a later date. We hope that the advice we have given you here makes it easier for you to create better comments and documentation in your code.
Acknowledgements
The author would like to thank Zoleka Hofmann for her critical comments while preparing this article.
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 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
2. Comments for Functions
3. Comments for Class
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.
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.
We can access the docstring of an entity using __doc__ attribute.
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.
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
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.
Summary
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.
What is the proper way to comment functions in Python?
Is there a generally accepted way to comment functions in Python? Is the following acceptable?
11 Answers 11
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
The correct way to do it is to provide a docstring. That way, help(add) will also spit out your comment.
That’s three double quotes to open the comment and another three double quotes to end it. You can also use any valid Python string. It doesn’t need to be multiline and double quotes can be replaced by single quotes.
This is the built-in suggested convention in PyCharm for describing function using docstring comments:
Use a docstring, as others have already written.
You can even go one step further and add a doctest to your docstring, making automated testing of your functions a snap.
A string literal that occurs as the first statement in a module, function, class, or method definition. Such a docstring becomes the __doc__ special attribute of that object.
All modules should normally have docstrings, and all functions and classes exported by a module should also have docstrings. Public methods (including the __init__ constructor) should also have docstrings. A package may be documented in the module docstring of the __init__.py file in the package directory.
String literals occurring elsewhere in Python code may also act as documentation. They are not recognized by the Python bytecode compiler and are not accessible as runtime object attributes (i.e. not assigned to __doc__ ), but two types of extra docstrings may be extracted by software tools:
How to Comment in Python
Home » SysAdmin » How to Comment in Python
Updated in July 2021
A key skill in writing code is the ability to use comments. Comments are lines that compilers and interpreters ignore that developers use to leave notes about the function of the code. Additionally, they can also be used to disable parts of the code.
This guide will show you how to use comments in Python effectively.
Python Comment Syntax
To add or mark a line as a comment, start with a hash sign (#) and a space:
Using the hash sign to start the line tells the system to ignore everything in that line. When the application runs, the program pretends like those lines don’t exist. However, you can still see it when you edit the file.
For example, in the Hello World program below:
The system runs the code print(«Hello, World») in line four, whereas the line above it explains what the code is supposed to do.
You can set any line as a comment, and use as many as you like. If your code has different blocks, you can use a comment to explain each one. For example:
Python Comment Block
Block comments are longer-form comments that consist of multiple lines in a row. A developer uses them to explain more complex code, especially when working in a team.
To mark a series of lines as a comment, add a hash sign + space at the beginning of each line:
Some text or code editors for programming (like Notepad++ or Atom) 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.
Python Multiline Comment
In general, it is recommended to use # at the beginning of each line to mark it as a comment. However, commenting a large section takes a lot of time and you may need a quick way to comment out a whole section. In such instances, you can use multi-line comments.
Multi-line strings do not work as traditional Python comments, since there is no official multi-line functionality. Instead, use multi-line strings wrapped inside triple-quote marks ( «»» ) to achieve a similar function.
Note: It is important that you correctly indent the triple-quote mark. If you don’t, you will see a syntax error.
This method creates a text constant with no function, not a true comment. As long as you don’t add anything that accesses that string of text, it works the same as a regular comment.
The triple-quotation mark can be tricky because in some circumstances it creates a docstring if a triple-quote:
If you place «»» in one of the places listed above, Python reads 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.
Python Inline Comment
You can comment in the same line as a piece of code using an inline comment. The best time to use this option is when explaining a complicated operation.
Use an inline comment to point out the exact spot you want to clarify. Add the standard hash sign + space to signify an inline comment:
Inline comments are used to add context for people 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.
Python Comment Out
Because comments render text invisible to the parser, you can use them to disable commands. Doing so lets you test segments of code with and without new additions.
For example, in this simple dice rolling program, there is a section that’s commented out. If you remove the hash sign, you enable the code to test it.
Why Are Comments Important In Python
Commenting can help you:
Python Code Comments Best Practices
AVOID:
You should now understand how (and why) to make comments in the Python language.
How To Write Comments in Python 3
Introduction
Comments are lines that exist in computer programs that are ignored by compilers and interpreters. Using comments in programs can make code more readable for humans, as it provides some information or explanation about what each part of a program is doing.
Depending on the purpose of your program, comments can serve as notes to yourself or reminders, or they can be written with the intention of other programmers being able to understand what your code is doing.
In general, it is a good idea to write comments while you are writing or updating a program as it is easy to forget your thought process later on, and comments written later may be less useful in the long term.
Prerequisites
You should have Python 3 installed and a programming environment set up on your computer or server. If you don’t have a programming environment set up, you can refer to the installation and setup guides for a local programming environment or for a programming environment on your server appropriate for your operating system (Ubuntu, CentOS, Debian, etc.)
Comment Syntax
Comments in Python begin with a hash mark ( # ) and whitespace character and continue to the end of the line.
Info: To follow along with the example code in this tutorial, open a Python interactive shell on your local system by running the python3 command. Then you can copy, paste, or edit the examples by adding them after the >>> prompt.
Generally, comments will look something like this:
Because comments do not execute, when you run a program you will not see any indication of the comment there. Comments are in the source code for humans to read, not for computers to execute.
In a “Hello, World!” program, a comment may look like this:
In a for loop that iterates over a list, comments may look like this:
Comments should be made at the same indent level as the code it is commenting. That is, a function definition with no indent would have a comment with no indent, and each indent level following would have comments that are aligned with the code it is commenting.
For example, here is how the again() function from the How To Make a Simple Calculator Program in Python 3 tutorial is commented, with comments following each indent level of the code:
Comments are made to help programmers, whether it is the original programmer or someone else using or collaborating on the project. If comments cannot be properly maintained and updated along with the code base, it is better to not include a comment rather than write a comment that contradicts or will contradict the code.
When commenting code, you should be looking to answer the why behind the code as opposed to the what or how. Unless the code is particularly tricky, looking at the code can generally tell what the code is doing or how it is doing it.
Block Comments
Block comments can be used to explain more complicated code or code that you don’t expect the reader to be familiar with. These longer-form comments apply to some or all of the code that follows, and are also indented at the same level as the code.
In block comments, each line begins with the hash mark and a single space. If you need to use more than one paragraph, they should be separated by a line that contains a single hash mark.
Here is an example of a block comment that defines what is happening in the main() function defined in the following:
Block comments are typically used when operations are less understandable and are therefore demanding of a thorough explanation. You should try to avoid over-commenting the code and should tend to trust other programmers to understand Python unless you are writing for a particular audience.
Inline Comments
Inline comments occur on the same line of a statement, following the code itself. Like other comments, they begin with a hash mark and a single whitespace character.
Generally, inline comments look like this:
Inline comments should be used sparingly, but can be effective for explaining tricky or complex parts of code. They can also be useful if you think you may not remember a line of the code you are writing in the future, or if you are collaborating with someone who you know may not be familiar with all aspects of the code.
For example, if you don’t use a lot of math in your Python programs, you or your collaborators may not know that the following creates a complex number, so you may want to include an inline comment about that:
Inline comments can also be used to explain the reason behind doing something, or some extra information, as in:
Comments that are made in line should be used only when necessary and when they can provide helpful guidance for the person reading the program.
Commenting Out Code for Testing
In addition to using comments as a way to document code, the hash mark can also be used to comment out code that you don’t want to execute while you are testing or debugging a program you are currently creating. That is, when you experience errors after implementing new lines of code, you may want to comment a few of them out to see if you can troubleshoot the precise issue.
Using the hash mark can also allow you to try alternatives while you’re determining how to set up your code. For example, you may be deciding between using a while loop or a for loop in a Python game, and can comment out one or the other while testing and determining which one may be best:
Commenting out code with the hash mark can allow you to try out different programming methods as well as help you find the source of an error through systematically commenting out and running parts of a program.
Conclusion
Using comments within your Python programs helps to make your programs more readable for humans, including your future self. Including appropriate comments that are relevant and useful can make it better for others to collaborate with you on programming projects and make the value of your code more clear.
From here, you may want to read about Python’s Docstrings in PEP 257 to provide you with more resources to properly document your Python projects.
Want to learn more? Join the DigitalOcean Community!
Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in our Questions & Answers section, find tutorials and tools that will help you grow as a developer and scale your project or business, and subscribe to topics of interest.
Tutorial Series: How To Code in Python
Introduction
Python is a flexible and versatile programming language that can be leveraged for many use cases, with strengths in scripting, automation, data analysis, machine learning, and back-end development. It is a great tool for both new learners and experienced developers alike.
Prerequisites
You should have Python 3 installed and a programming environment set up on your computer or server. If you don’t have a programming environment set up, you can refer to the installation and setup guides for a local programming environment or for a programming environment on your server appropriate for your operating system (Ubuntu, CentOS, Debian, etc.)