18
JulComments in Python -Types, How to Write, Uses
Comments in Python are used to add explanatory notes within the code, making it easier for developers to read and understand. During program execution, the Python interpreter ignores any comments.
In this Python tutorial, we’ll explore the types of comments in Python, how to write effective comments, and their practical application
What are Comments in Python?
Comments in Python are notes written within the code to explain its function, but they are ignored by the computer during execution. The '#' symbol denotes single-line comments, while triple quotes (''' or """) are used for multiline strings, often as docstrings. These are not true comments and can be stored in memory if not handled correctly. Comments help make code clearer for both the programmer and others, and they allow developers to temporarily disable specific lines without deleting them. Importantly, comments do not influence the program's operation. They are also useful for documenting functions, variables, and other key parts of the code.
Syntax for Creating a Comment
#This is a comment
print("Welcome to Scholarhat!")
Explanation:
- Python ignores the line starting with #, while the second line prints a message to the screen.
Types of Comments in Python:
There are three types of comments in the Python programming language, those are:
- Single-line Comments
- Multiple line comments in Python
- Docstring Comments
1. Single line Comment in Python
- A single-line comment in Python begins with the hash symbol (#) and continues to the end of the line.
- If the comment is multiple lines, place a hashtag on the next line and continue with the Python Comments.
- Single-line comments in Python have proven beneficial for providing quick explanations for Variables in Python, Function Declarations in Python, and expressions.
Example of Single Line Comment in Python
# This is a single line comment in python
print ("Hello, Scholarhat!")
This Python code in the Python Compiler outputs "Hello, World!" to the console and contains a single-line comment denoted by the "#" symbol, which is used to add explanations or comments to the code but is disregarded when the code is executed.
Output
Hello, Scholarhat!
Read More: 50 Python Interview Questions and Answers |
2. Multiple-line Comments in Python
Multiline comments are not supported in Python. However, there are other methods for writing multiline comments.
Method 1: Using multiple # symbols
In Python, we can construct multiline comments by starting each line with a # symbol.. Every single line will be regarded as a separate comment.Example of Multiple Line Comment in Python
# This is a multi-line comment
# created by using multiple
# single-line comments.
print ("Hello, Scholarhat!")
This Python code in the Python Editor includes a multiline comment encased in triple single quotes and acts as an explanation or documentation block while simultaneously being ignored during execution. The message "Hello, World!" is then printed to the console.
Output
Hello, World!
Read More: Python Developer Salary |
Method 2: Using multiple # symbols
- Python String literals, Triple-quoted string literals (''' or """) can also be used to mimic multiline comments.
- For multi-line strings, these triple quotes are typically utilized.
- If not assigned to a variable, these strings are ignored, but they still exist as string objects in memory during runtime.
- Avoid using it as a comment unless it's part of a docstring.
- If a string is not allocated to any Python Function or Python Variable, the Python interpreter ignores it.
Example of Using String Literals as Comments
'''
This is a multi-line string literal.
It looks like a comment but is stored in memory.
Avoid using it as a comment unless it's part of a docstring.
'''
print("Hello, Scholarhat!")
3. Docstring in Python
- Docstrings are a built-in feature of Python that allows you to document modules, methods, functions, objects, and classes.
- Three quotes (''' or " ") are used to write them in the first line following the definition of a module in Python, function of Python, method, etc.
- The interpreter will not recognize it as a docstring if you do not use it in the first line.
- Additionally, you can use the __doc__ attribute to retrieve docstrings.
Example of Docstring in Python
def greet(name):
"""Greets the specified person."""
print(f"Hello, {name}!")
greet("Scholarhat")
The greet function in this code has a single parameter, name. Using f-strings, the greet function prints a customized greeting on the terminal.
Output
Hello, Ram!
How to Write Good Comments in Python?
To write good comments in Python, we provide you with some suggestions. Please follow them:
- Please make sure comments are concise.
- Avoid making generic comments; only include them if they provide more context.
- Write comments that, rather than focusing on specifics, highlight the general goal of a function or method.
- Excellent comments are self-explanatory.
- Avoid making repeated comments.
- Using a comment in Python effectively makes debugging and collaboration easier.
What Are Comments in Python Used For?
In Python, comments start with a hash symbol (#) and continue until the end of the line. However, hash characters in a string are not regarded as comments. There are three methods to create a comment: as a separate line, next to the relevant code statement, or as a multi-line comment block.
Python comments are useful in many ways, including these key purposes:
- Enhancing code readability
- Clarifying code for others
- Making it easier to understand after a long time
- Adding references or resources
- Facilitating code reuse
Why Are Comments Important in Python?
Comments are important in Python because they improve code readability and help in understanding the logic behind the code. They make programming more efficient and collaborative.
- Documentation: Comments explain the purpose of functions, classes, or code sections, helping understand complex logic.
- Readability: Well-commented code is easier to read, making it simple to understand even after a long time
- Debugging: Comments help in finding and fixing bugs by allowing parts of the code to be temporarily disabled
- Collaboration:I n teamwork, comments make code easier to share and review, improving teamwork and project flow.
Prevent Executing Code Using Comments
Docstrings vs. Comments in Python
Feature | Docstrings (""" """) | Comments (#) |
Purpose | Describe the purpose of a module, function, or class | Explain specific lines or blocks of code |
Syntax | Enclosed in triple quotes (""" """ or ''' ''') | Starts with # |
Retrieval | Can be accessed using help() or .__doc__ | Not retrievable at runtime |
Placement | At the beginning of modules, functions, or classes | Anywhere in the code (inline or above the code) |
Use Case | Used for documentation and auto-generated API docs | Used for clarifying logic or disabling code temporarily |
Best Practices for Writing Comments
Here are several best practices for writing comments that are:
1. Keep Comments Relevant and Concise:
Write comments that explain the why, not the how. The code itself should convey how.Example
# Check if the user input is valid
if user_input.isdigit():
print("Valid input")
2. Use Proper Grammar and Punctuation:
Clear and professional comments are easier to read.Example
# Calculate the area of a circle
radius = 5
area = 3.14 * radius ** 2
3. Avoid Redundant Comments:
Do not write comments that simply restate the code.Bad Example:
# Increment the value of x by 1
x = x + 1
Better Example:
# Adjust x to account for one additional item
x = x + 1
4. Update Comments as Code Changes:
Outdated comments can confuse readers.Example
# This function multiplies two numbers
def calculate(a, b):
return a + b # The comment should reflect the addition, not multiplication
5. Avoid Excessive Comments:
Do not clutter your code with unnecessary comments. Instead, write clear and self-explanatory code.Example
# Initialize a list with even numbers
even_numbers = [2, 4, 6, 8, 10]
6. Use TODO Comments for Pending Tasks:
Mark areas needing further work withTODO
.Example
# TODO: Optimize this loop for large datasets
for i in range(1000):
print(i)
By following these practices, your comments will be meaningful, helpful, and maintainable!
Advantages of Using Comments in Python
Python comments offer several advantages. Their main advantages are:
Summary
In this article, we explored how Python comments play a vital role in documenting our code. Comments makes our code easier to understand. They help to explain what is going on in a program and can be used to prevent errors from happening. When you use comments, it is important to keep them up to date so that they accurately reflect the code.
If you prefer a structured learning approach, you may also consider Python certification, which provides comprehensive guidance and resources to help you master the language.
Test your skills by following MCQs
Dear learners, attempt these MCQ questions and know your abilities.
Q 1: Which symbol is used for single-line comments in Python?
To consider all your demands and the well-being of our students, we provide you with free tech courses that will surely help you in your development journey.
FAQs
Take our Python skill challenge to evaluate yourself!

In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.