FY 2024-25 End Sale: Get Upto 40% OFF on Live Training! Offer Ending in
D
H
M
S
Get Now
Comments in Python -Types, How to Write, Uses

Comments in Python -Types, How to Write, Uses

11 Mar 2025
Beginner
4.98K Views
22 min read
Learn with an interactive course and practical hands-on labs

Free DSA Online Course with Certification

Comments in Python are essential for making your code readable and maintainable. Comments help explain what your code does, making it easier for others (and your future self) to understand. In Python, you can use the # symbol for single-line comments and triple quotes (''' or """) for multi-line comments, although the latter is typically used for docstrings. A comment in Python is used to annotate code for better understanding.

In this Python Tutorial, we explore comments in Python, including types of comments in Python, how to write good comments in Python, use of Python comments, and a lot more. Whether you're a beginner or an experienced programmer, using comments correctly will improve your coding efficiency. Additionally, enrolling in Python for Data Science and AI Certification can help you enhance your Python skills and apply them effectively in data science and AI projects. Developers use comments in Python to explain complex logic in their programs. A comment in Python starts with the # symbol and extends to the end of the line.

What are Comments in Python?

Comments in Python are notes written in code to explain what the code does, but the computer ignores them when running the program. They start with a # symbol and are helpful for making the code easier for yourself and others to understand. The comment in Python feature allows programmers to disable specific lines of code without deleting them. A comment in Python does not affect the execution of the program. You can use a comment in Python to document functions, variables, and important code sections.

Syntax for Creating a Comment

#This is a comment
print("Welcome to Scholarhat!")

Types of Comments in Python:

There are three types of comments in the Python programming language, those are:

  1. Single-line Comments
  2. Multiple line comments in Python
  3. Docstring Comments

Comment in Python

1. Single line Comment in Python

  • A single-line comment in Python begins with the hashtag (#) 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.

Using multiple hashtags (#) in multiline comments

In Python, we can construct multiline comments by using several hashtags (#). Every single line will be regarded as a separate comment.

Example of Multiple Line Comment in Python

        '''
This is a multiline
comment.
'''
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

3. Using Python's string literals

  • Python String literals, which can be used with triple quotes, either ''' or ", are another method for implementing this.
  • For multi-line strings, these triple quotes are typically utilized. However, we can use it as a comment if we don't assign it to any variables or functions.
  • 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!")

4. Docstring in Python

  • Docstrings are a built-in feature of Python that allows you to remark on 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

You can use comments to prevent code from running by adding a # at the beginning of a line. This is useful for testing, debugging, or temporarily disabling parts of the code.

Docstrings vs. Comments in Python

FeatureDocstrings (""" """)Comments (#)
PurposeDescribe the purpose of a module, function, or classExplain specific lines or blocks of code
SyntaxEnclosed in triple quotes (""" """ or ''' ''')Starts with #
RetrievalCan be accessed using help() or .__doc__Not retrievable at runtime
PlacementAt the beginning of modules, functions, or classesAnywhere in the code (inline or above the code)
Use CaseUsed for documentation and auto-generated API docsUsed 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 with TODO.

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:

1. Enhanced Readability: Comments make the code easier to understand by explaining each section, helping in maintenance and teamwork
2. Self-Documenting Code: Using clear variable and function names makes the code understandable without extra comments, reducing the need for documentation
3. Better Collaboration: Well-documented code helps team members work together efficiently, ensuring smooth project development.
4. Better Debugging: Clear comments and structured code help identify and fix errors quickly, making debugging easier.
5. Code Control: Proper comments and version control keep the code organized, making updates and tracking changes simpler.
6. Logic Explanation: Explaining the thought process behind the code with comments makes it easier to follow and understand.
7. Code Maintainability: Clean, well-structured code ensures easy updates and fixes, saving time in long-term projects.
8. Code Reuse: Writing modular and well-documented code allows it to be reused in different projects, improving efficiency.

Summary

Python comments are very important. 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.

Python Comments Quiz

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.

Top Most Asked Topics
Libraries in Python- Complete Resolution
An Easy Way To Understand Python Slicing
Python Features: A Comprehensive Guide for Beginners
File Handling In Python: Python File Operations

FAQs

The best Python comments are clear and succinct, and describe why (not what) the code accomplishes.

Use code review procedures and develop commenting guidelines within your team to maintain uniformity.

Yes, software like Pylint and Flake8 can aid in upholding standards for commenting.

Use comments to explain intricate logic, describe classes and functions, and give non-obvious code context.
Share Article
About Author
Sakshi Dhameja (Author and Mentor)

She is passionate about different technologies like JavaScript, React, HTML, CSS, Node.js etc. and likes to share knowledge with the developer community. She holds strong learning skills in keeping herself updated with the changing technologies in her area as well as other technologies like Core Java, Python and Cloud.

Accept cookies & close this