What is Comments in Python - Types, How to Write, Uses

What is Comments in Python - Types, How to Write, Uses

12 Dec 2024
Beginner
4.16K Views
10 min read
Learn with an interactive course and practical hands-on labs

Free DSA Online Course with Certification

Comments in Python

Have you looked at your own code after a week and wondered, 'What was I even thinking here?' If yes, then comments in Python are about to become your new helper. Comments are like those helpful sticky notes you leave for future-you (or anyone else reading your code). They're perfect for explaining tricky logic, marking areas to revisit, or just making your code easier to follow.

Are you ready to embark on a comprehensive Python Tutorial to master the basics of Python commenting and make your code easier to read? If so, you're in luck! In this article, we'll take an in-depth look at commenting functions in Python, python comments, Comments in Python, creating Comments in Python, and Multiline Comments in Python, and provide tips on making sure that your comment style is clear and concise.

What are Comments in Python?

The lines of code in Python that the interpreter ignores while the program is running are called comments.A comment is a line of text within a program that is not executed.Python code can be explained with comments.The code can be made easier to read by adding comments.

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

Types of Comments 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, World!") 

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, World!

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, World!")

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, Python!")

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, 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("Ram")

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?

  • 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.

Use of Python Comment

1. Make the code simpler to comprehend:

  • Coding comments will make it simpler to refer to in the future.
  • Additionally, the code will be simpler for other developers to grasp.

2. Using Comments to Help with Debugging:

  • Instead of eliminating the line of code that results in the error if we encounter one when executing the program, we can remark it.

Best Practices for Writing Comments

1. Keep Comments Relevant and Concise:

Write comments that explain the why, not the how. The code itself should convey the 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:

  • Readability of Code
  • An explanation of the project's code or metadata
  • Stop the code from running
  • Incorporating resources
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.

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