How to Use Comments in Python

A Python comment is a line of text that the Python interpreter ignores during execution. This means comments do not affect how your program runs. They serve as notes for you and other developers.

Python comments help you make your code clear. They explain complex logic or the purpose behind a section of code. You can use comments to save time when you revisit your code later or when someone else reads it.

What is a Python Comment?

A Python comment is a line of text starting with a hash symbol (#) that the interpreter skips during program execution. This text is for human readers only.

For example, this is a comment:

# This line is a comment and will be ignored by Python
print("Hello, world!")

3 Ways to Use Comments in Python

You use different types of comments for different purposes. Python provides clear ways to add comments to your code.

1. Single-Line Comments

A single-line comment begins with a hash symbol (#). Everything after the # on that line is a comment. You use these for short explanations about a specific line or small block of code.

You can place a single-line comment on its own line:

# Initialize a counter variable
counter = 0

Or, you can put it on the same line as your code:

user_name = "Alice"  # Store the user's name

2. Multi-Line Comments (Block Comments)

Python does not have a dedicated syntax for multi-line comments. You can achieve multi-line comments in two ways.

  • Multiple single-line comments: You place a # at the beginning of each line you want to comment out.
# This is the first line of a multi-line comment.
# It explains a complex function.
# You can read it over multiple lines.
def calculate_total(price, quantity):
    return price * quantity
  • String Literals (Docstrings): You use triple quotes (''' or """) to create a multi-line string. If this string is not assigned to a variable, the Python interpreter ignores it. This makes it a multi-line comment.
"""
This is a multi-line comment.
It provides detailed information about
the purpose of this script.
"""
item_list = []
Academy Pro

Python Programming Course

In this course, you will learn the fundamentals of Python: from basic syntax to mastering data structures, loops, and functions. You will also explore OOP concepts and objects to build robust programs.

11.5 Hrs
51 Coding Exercises
Learn Python Programming

3. Docstrings

A docstring is a special type of multi-line comment. You use docstrings to document modules, functions, classes, and methods. Docstrings are enclosed in triple quotes ("""Docstring content""" or '''Docstring content'''). They appear immediately after the def or class statement.

Docstrings help other developers understand what your code does. They are crucial for creating clear and usable APIs.

Here is an example of a docstring for a function:

def calculate_area(length, width):
    """
    Calculates the area of a rectangle.

    Args:
        length (float): The length of the rectangle.
        width (float): The width of the rectangle.

    Returns:
        float: The calculated area of the rectangle.
    """
    return length * width

You can get the docstring by calling help() on the function or accessing its __doc__ attribute:

print(calculate_area.__doc__)

Best Practices for Writing Python Comments

Good comments improve your code’s quality. They make your code easy to understand and maintain. Here are 5 practices for writing effective comments:

  • Explain the “Why,” Not Just the “What”: Your code already shows what it does. Comments should explain why you made certain design choices. For instance, instead of # Add 1 to x, write # Increase counter to handle edge case.
  • Keep Comments Concise: Short, clear comments are better. Avoid long explanations. If a section needs extensive explanation, break it into smaller functions.
  • Update Comments Regularly: Outdated comments are worse than no comments. When you change your code, always update the associated comments to reflect the changes.
  • Avoid Obvious Comments: Do not comment on code that is self-explanatory. For example, x = 10 # Assign 10 to x adds no value. Focus your comments on complex logic.
  • Use Docstrings for Public APIs: Always write docstrings for public modules, functions, and classes. They serve as essential documentation for anyone using your code. Follow PEP 257 guidelines for consistent docstring formatting.

You can also use comments when debugging:

# debug_mode = True
# if debug_mode:
#     print("Debugging activated")
Avatar photo
Great Learning Editorial Team
The Great Learning Editorial Staff includes a dynamic team of subject matter experts, instructors, and education professionals who combine their deep industry knowledge with innovative teaching methods. Their mission is to provide learners with the skills and insights needed to excel in their careers, whether through upskilling, reskilling, or transitioning into new fields.

Academy Pro Subscription

Grab 50% off
on Top Courses - Free Trial Available

×
Scroll to Top