- How To Write Comments in Python 3
- Prerequisites
- Comment Syntax
- Block Comments
- Inline Comments
- Commenting Out Code for Testing
- Conclusion
- Tutorial Series: How To Code in Python
- Introduction
- Prerequisites
- Python Comments
- Introduction to Python comments
- Python block comments
- Python inline comments
- Python docstrings
- 1) One-line docstrings
- 2) Multi-line docstrings
- Python multiline comments
- Summary
How To Write Comments in Python 3
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:
# Print “Hello, World!” to console print("Hello, World!")
In a for loop that iterates over a list, comments may look like this:
# Define sharks variable as a list of strings sharks = ['hammerhead', 'great white', 'dogfish', 'frilled', 'bullhead', 'requiem'] # For loop that iterates over sharks list and prints each string item for shark in sharks: print(shark)
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:
... # Define again() function to ask user if they want to use the calculator again def again(): # Take input from user calc_again = input(''' Do you want to calculate again? Please type Y for YES or N for NO. ''') # If user types Y, run the calculate() function if calc_again == 'Y': calculate() # If user types N, say good-bye to the user and end the program elif calc_again == 'N': print('See you later.') # If user types another key, run the function again else: again()
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:
# The main function will parse arguments via the parser variable. These # arguments will be defined by the user on the console. This will pass # the word argument the user wants to parse along with the filename the # user wants to use, and also provide help text if the user does not # correctly pass the arguments. def main(): parser = argparse.ArgumentParser() parser.add_argument( "word", help="the word to be searched for in the text file." ) parser.add_argument( "filename", help="the path to the text file to be searched through" ) ...
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:
[code] # Inline comment about the code
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:
z = 2.5 + 3j # Create a complex number
Inline comments can also be used to explain the reason behind doing something, or some extra information, as in:
x = 8 # Initialize x with an arbitrary number
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:
import random number = random.randint(1, 25) # number_of_guesses = 0 for i in range(5): # while number_of_guesses < 5:print('Guess a number between 1 and 25:') guess = input() guess = int(guess) # number_of_guesses = number_of_guesses + 1 if guess number: print('Your guess is too low') if guess > number: print('Your guess is too high') if guess == number: break if guess == number: print('You guessed the number!') else: print('You did not guess the number. The number was ' + str(number))
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 deploy your application quickly? Try Cloudways, the #1 managed hosting provider for small-to-medium businesses, agencies, and developers — for free. DigitalOcean and Cloudways together will give you a reliable, scalable, and hassle-free managed hosting experience with anytime support that makes all your hosting worries a thing of the past. Start with $100 in free credits!
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.)
Python Comments
Summary: in this tutorial, you’ll learn how to add comments to your code. And you’ll learn various kinds of Python comments including block comments, inline comments, and documentation string.
Introduction to Python comments
Sometimes, you want to document the code that you write. For example, you may want to note why a piece of code works. To do it, you use the comments.
Typically, you use comments to explain formulas, algorithms, and complex business logic.
When executing a program, the Python interpreter ignores the comments and only interprets the code.
Python provides three kinds of comments including block comment, inline comment, and documentation string.
Python block comments
A block comment explains the code that follows it. Typically, you indent a block comment at the same level as the code block.
To create a block comment, you start with a single hash sign ( # ) followed by a single space and a text string. For example:
# increase price by 5% price = price * 1.05
Code language: Python (python)
Python inline comments
When you place a comment on the same line as a statement, you’ll have an inline comment.
Similar to a block comment, an inline comment begins with a single hash sign ( # ) and is followed by a space and a text string.
The following example illustrates an inline comment:
salary = salary * 1.02 # increase salary by 2%
Code language: Python (python)
Python docstrings
A documentation string is a string literal that you put as the first lines in a code block, for example, a function.
Unlike a regular comment, a documentation string can be accessed at run-time using obj.__doc__ attribute where obj is the name of the function.
Typically, you use a documentation string to automatically generate the code documentation.
Documentation strings is called docstrings.
Technically speaking, docstrings are not the comments. They create anonymous variables that reference the strings. Also, they’re not ignored by the Python interpreter.
Python provides two kinds of docstrings: one-line docstrings and multi-line docstrings.
1) One-line docstrings
As its name implies, a one-line docstring fits one line. A one-line docstring begins with triple quotes ( «»» ) and also ends with triple quotes ( «»» ). Also, there won’t be any blank line either before or after the one-line docstring.
The following example illustrates a one-line docstring in the quicksort() function:
def quicksort(): """ sort the list using quicksort algorithm """ .
Code language: Python (python)
2) Multi-line docstrings
Unlike a one-line docstring, a multi-line docstring can span multiple lines. A multi-line docstring also starts with triple quotes ( «»» ) and ends with triple quotes ( «»» ).
The following example shows you how to use multi-line docstrings:
def increase(salary, percentage, rating): """ increase salary base on rating and percentage rating 1 - 2 no increase rating 3 - 4 increase 5% rating 4 - 6 increase 10% """
Code language: Python (python)
Python multiline comments
Python doesn’t support multiline comments.
However, you can use multi-line docstrings as multiline comments. Guido van Rossum, the creator of Python, also recommended this.
It’s a good practice to keep your comment clear, concise, and explanatory. The ultimate goal is to save time and energy for you and other developers who will work on the code later.
Summary
- Use comments to document your code when necessary.
- A block comment and inline comment starts with a hash sign ( # ).
- Use docstrings for functions, modules, and classes.