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
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:
- Make sure your comment begins at the same indent level as the code it's about.
- Begin with the hashtag (#) and a space. The hash character tells the interpreter to ignore the rest of the line of code.
- Write your comment.
- Close your comment with a newline. Python will start reading your code again after the line containing the comment ends.
Example:
PYTHON
12345
print(5 + 10)y = 20 * 5print(y)# Hi, this is a commentprint("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?
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
12
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
123
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
123
statetax = 1.0625 # State sales tax rate is 6.25% through Jan. 1citytax = 1.01 # City sales tax rate is 1% through Jan. 1specialtax = 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:
PYTHON
12
# 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:
- Make sure your docstring begins at the same indentation level as the scope.
- Use a triple quote to start the string, followed by a phrase beginning with a capital letter and ending with a period.
- 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
12345
'''This is a multilinecomment using string literalswith 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 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.
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
123
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.
- Style Guide for Python Code
- Being a Python Developer: What They Can Do, Earn, and More
- Python syntax tutorial
- Python traceback tutorial
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.
FAQs
How do you comment on single line and multi-line in Python? ›
To comment out multiple lines in Python, you can prepend each line with a hash ( # ). With this approach, you're technically making multiple single-line comments. The real workaround for making multi-line comments in Python is by using docstrings.
How do you efficiently comment out a large block of 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.
How do you inline a comment in Python? ›In Python, we use the hash ( # ) symbol to start writing a comment. The comment begins with a hash sign ( # ) and whitespace character and continues to the end of the line.
Which of these is used in Python for multiline comments line comment? ›Hash character(#) is used to comment the line in the Python program. Comments does not have to be text to explain the code, it can also be used to prevent Python from executing code. The hash character should be placed before the line to be commented.
How do you write single-line comments and multi-line comments? ›We looked at single-line and multi-line comment in C#. Single-line comments end at the first end-of-line following the // comment marker. You can place it at the top of the code statement or after the code statement. If it's after a code statement, whatever text following it is regarded as the comment.
What are the 2 types of comments in Python? ›What Are the Different Types of Comments in Python? There are three types of comments: single-line, multi-line, and docstring comments.
How do you comment a big chunk of code? ›- In the C/C++ editor, select multiple line(s) of code to comment out.
- To comment out multiple code lines right-click and select Source > Add Block Comment. ( CTRL+SHIFT+/ )
- To uncomment multiple code lines right-click and select Source > Remove Block Comment. ( CTRL+SHIFT+\ )
- Rule 1: Comments should not duplicate the code.
- Rule 2: Good comments do not excuse unclear code.
- Rule 3: If you can't write a clear comment, there may be a problem with the code.
- Rule 4: Comments should dispel confusion, not cause it.
Inline comments allow you to leave text directly on top of your student's paper. Click anywhere on a paper to reveal the in-context marking tool; choose the T icon and then begin typing your comment. The comment will automatically be saved.
How do you write multiple lines in Python? ›Multi-line Statement in Python:
In Python, the statements are usually written in a single line and the last character of these lines is newline. To extend the statement to one or more lines we can use braces {}, parentheses (), square [], semi-colon “;”, and continuation character slash “\”.
How do you insert an inline comment? ›
Add inline comments
Highlight the text you want to comment on. Select the add comment button that appears above the highlighted text.
- From the main menu, select Code | Comment with Line Comment.
- Press Ctrl+/ .
To comment out an entire block of code: Select the code and select Toggle Line Comment(s) from the context menu.
How do you declare a multiline comment? ›Java Multi-line Comments
Multi-line comments start with /* and ends with */ . Any text between /* and */ will be ignored by Java.
Single-Line Comment
n = 50 #Store 50 as value into variable n. In the above example program, the first line starts with the hash symbol, so the entire line is considered a comment. In the second line of code, "N = 50" is a statement, and after the statement, the comment begins with the # symbol.
Full line comments take a complete line while Inline comments share the line with a statement or expression.
What are the comments standards in Python? ›Use inline comments sparingly. An inline comment is a comment on the same line as a statement. Inline comments should be separated by at least two spaces from the statement. They should start with a # and a single space.
Do comments make code more readable? ›The most obvious and immediate benefit of writing good comments is that they make code easier for others to understand.
How do I become more proficient in Python? ›You should first concentrate on fundamental Python principles such as coding, data structures, and object-oriented programming. Try learning about real Python projects; the more you read about them, the more proficient you will become. Python Crash Course is another choice for speeding up your learning.
Do comments make code slower Python? ›Having comments will slow down the startup time, as the scripts will get parsed into an executable form. However, in most cases comments don't slow down runtime. Additionally in python, you can compile the .
How do you comment faster or code? ›
- On Windows, the shortcut is: CTRL + /
- On Mac, the shortcut is: Command + /
The leading characters // are added to the beginning of each line when commenting one or more lines of code. You can also block comment multiple lines of code using the characters /* */ .
How multiline and single line comments are given in C? ›Single Line comment: ctrl + / (windows) and cmd + / (mac) Multi line comment: ctrl + shift + / (windows) and cmd + shift + / (mac)