View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

Comments in Python: Talking to Your Future Self

Updated on 30/05/20253,998 Views

Whether you're a beginner learning Python or someone debugging a late-night college project (with chai in one hand and stress in the other), one underrated skill can save you hours of confusion—writing clear comments. In programming, comments act like sticky notes to your future self or to your teammates. They don’t change how your code runs, but they can definitely change how your code is understood. Think of them as subtitles in a suspense thriller—helpful, especially when the plot (or logic) gets too twisty.

In this article, we'll break down everything about comments in Python—what they are, how to use them effectively, the different types, best practices, and even some rookie mistakes to avoid. We’ll also throw in real-world examples featuring folks like Rajat and Anjali to help you relate better. Whether you're prepping for a Python exam, working on a project, or just tired of coming back to your own code that reads like a mystery novel, this guide is for you.

Pursue our Software Engineering courses to get hands-on experience!

What Are Comments in Python and Why Do We Use Them?

Comments in Python are non-executable lines in your code that help you or others understand what the code is doing. The Python interpreter completely ignores comments when running the program—they’re there for humans, not machines.

Imagine you’re sharing a recipe with a friend, and you jot down, “Add a pinch of salt (don’t overdo it like last time).” That side note is a comment. It won’t change the taste of the recipe, but it’ll definitely help your friend avoid a disaster. Similarly, in code, comments explain the “why” behind the “what.”

Power up your professional growth with these exceptional courses.

Why do we use comments in Python?

  • To explain complex logic: Not every line of code is self-explanatory. A comment can break down your logic into digestible bites.
  • To improve readability: Comments make your code easier to follow, especially in team projects or open-source work.
  • To debug or disable code temporarily: You can comment out lines while testing or fixing issues.
  • To leave reminders: Think of it as a sticky note—"Fix this before final submission!"

Example:

# Calculate the area of a circle
radius = 7
area = 3.14 * radius ** 2
print("Area:", area)

Output:

Area: 153.86

Explanation: The comment above the calculation clarifies what the code is doing. Without it, a beginner might wonder, “Why are we multiplying 3.14 and squaring the radius?”

Tip: When you revisit your own code after a few weeks—or if Aniket picks it up for review—clear comments can save both of you from a lot of head-scratching.

Still new to Python? You might want to brush up on the introduction to Python programming to understand how code flows.

Types of Comments in Python

Python offers a few simple yet effective ways to include comments in your code. Depending on the situation, you may want to explain a single line, describe a block of logic, or document a function’s purpose. Let’s explore the main types:

1. Single-Line Comments

These comments occupy one line and start with a # symbol. Anything after the # on that line is treated as a comment.

# This is a single-line comment

name = "Priya"  # This is an inline comment

Explanation: In the first line, the entire line is a comment. In the second, the comment appears after an executable statement. Python ignores everything after the #.

Want to go deeper into the logic of your programs? Check out how Python variables and data types work behind the scenes.

2. Multi-Line Comments

Python doesn't have a specific multi-line comment syntax like some other languages, but you can create multi-line comments using consecutive single-line # symbols.

# This is a multi-line comment

# It spans over multiple lines

# and is ignored by Python

Alternatively, some developers use triple-quoted strings (''' or """) for multi-line comments, though this is not the official way.

'''

This is also treated like a comment

but technically it's a multi-line string

that is not assigned to any variable

'''

Note: Using triple quotes for commenting is discouraged unless you're writing docstrings. It's better to stick to # for clarity and best practice.

3. Docstrings (Documentation Strings)

These are used to document Python functions, classes, or modules. They use triple quotes (""") and are placed right after the definition line.

def greet(name):
    """
    This function greets the person passed as a parameter.
    """
    print("Hello,", name)

Explanation: This string becomes the official documentation for the function. You can access it using the .__doc__ attribute.

print(greet.__doc__)

Output:

This function greets the person passed as a parameter.

Each type of comment serves a different purpose. Once you know when and how to use them, your code starts to speak more clearly to anyone who reads it—including the future you.

How to Write Single-Line Comments in Python?

Writing single-line comments in Python is as easy as writing a WhatsApp message—just simpler syntax. You start with a # symbol followed by your message. Python ignores everything after the # on that line.

Syntax:

# This is a single-line comment

Example 1: Explaining a Line of Code

# Assigning age to Rajat

age = 21

Explanation: The comment helps anyone reading the code understand that the variable age holds Rajat’s age. This might seem obvious in a small program, but in large applications, it becomes crucial.

Example 2: Inline Comments

total_marks = 450  # Marks out of 500

Explanation: You can write comments on the same line as code. This is especially useful for giving context without cluttering up your script.

When to Use Single-Line Comments?

  • To summarize what a line/block of code does.
  • To explain tricky logic or unusual choices.
  • To temporarily disable a line of code while testing.

Example 3: Disabling Code Temporarily

# print("This line is not executed")
print("This one is executed")

Output:

This one is executed

Explanation: The first print statement is ignored because it’s commented out. This is a handy trick when debugging or testing different versions of code.

Tip: Avoid writing obvious comments like # Add two numbers above sum = a + b. Instead, explain why something is done, not what—your code already says what.

How to Add Multi-Line Comments in Python the Right Way?

Unlike some languages that provide a dedicated syntax for multi-line comments (like /* */ in C or Java), Python takes a simpler and more flexible route. While there's no official multi-line comment block syntax, Python allows two common and accepted ways to write multi-line comments.

Method 1: Using Multiple Single-Line Comments

This is the most widely used and recommended approach. You simply use # at the beginning of each line.

# This is a multi-line comment
# explaining how to calculate percentage
# from marks obtained and total marks.

marks_obtained = 420
total_marks = 500
percentage = (marks_obtained / total_marks) * 100
print("Percentage:", percentage)

Output:

Percentage: 84.0

Explanation: Each line that starts with # is treated as a separate comment. This keeps things clean and ensures you're following best practices.

Method 2: Using Triple-Quoted Strings

Triple quotes (''' or """) can be used to write comment-like blocks. These are actually multi-line string literals, and Python ignores them only if they’re not assigned to a variable or used as docstrings.

'''
This is a multi-line comment
created using triple quotes.
It is not stored or executed.
'''
print("Code is running.")

Output:

Code is running.

Explanation: While Python doesn’t treat triple quotes as true comments, they behave like comments if placed where they’re not assigned or executed. However, this is more of a workaround than a best practice.

The image depicts Python Commenting Methods

Tip: Stick with # for actual commenting and use triple quotes only for documentation strings or placeholder comments in early development.

What Are Docstrings in Python and How Are They Different?

Docstrings, short for documentation strings, are a special type of comment used specifically to describe functions, classes, and modules. They help other developers (or your future self) understand what a particular block of code is supposed to do—without needing to dive into the logic line by line.

While regular comments are meant for clarity and annotation, docstrings are meant for documentation and discoverability. That’s why Python allows them to be accessed programmatically using tools like help() or the .__doc__ attribute.

Syntax for Docstrings

Docstrings are written using triple quotes (""" or ''') and are placed directly below the definition line of a function, class, or module.

def greet(name):
    """
    Greets the person with the provided name.
    """
    print("Hello,", name)

Accessing a Docstring

print(greet.__doc__)

Output:

Greets the person with the provided name.

Explanation: Unlike regular comments, a docstring becomes an actual attribute of the object it's documenting. This is helpful when you're using IDEs or tools that generate documentation automatically.

Docstrings for Classes

class Student:
    """
    Represents a student with name and roll number.
    """
    def __init__(self, name, roll):
        self.name = name
        self.roll = roll
You can fetch this using:
print(Student.__doc__)

Output:

Represents a student with name and roll number.

Key Differences Between Comments and Docstrings

Feature

Comments (#)

Docstrings (""" """)

Purpose

Explain code logic

Document functions, classes, or modules

Syntax

# at the beginning

Triple quotes below the definition line

Execution

Completely ignored by Python

Stored as __doc__ attribute

Use Case

For developers only

For developers and documentation tools

Tip: Use regular comments for in-line or block annotations. Use docstrings when you want your code to be self-documented, especially in larger or collaborative projects.

Also, if you're working with user input, you’ll notice that understanding comment placement helps when you're building interactive programs. Explore how to manage that in our guide on taking input in Python.

Where Should You Use Comments in Python Code?

Knowing where to place comments is just as important as knowing how to write them. Strategic commenting improves code clarity, saves time during debugging, and helps teammates understand your work faster.

Here are the key areas where you should use comments effectively:

1. At the Beginning of Scripts or Files

Add a brief overview of what the entire program or script does. This helps anyone reading your code get the big picture immediately.

# This script calculates the monthly expenses and savings of a family

2. Before Complex or Non-Obvious Logic

When your code performs something tricky or unintuitive, a comment can clarify the thought process behind it.

# Using the formula for compound interest to calculate total savings

total = principal * (1 + rate) ** time

3. To Explain Magic Numbers or Constants

If you use specific values (like 3.14 for pi or 500 as max marks), add a comment explaining why.

pi = 3.14  # Approximate value of Pi used in circle area calculation

4. Before Function or Class Definitions (If Not Using Docstrings)

If you skip docstrings, at least add a short comment describing the purpose of the function or class.

# Function to calculate factorial of a number

def factorial(n):

    ...

5. To Temporarily Disable Code

During debugging or testing, you might comment out certain lines without deleting them.

# print("Debug info: value of x =", x)

6. To Leave Reminders or TODOs

Comments are useful for marking areas that need improvement or further work.

# TODO: Optimize this loop for better performance

Best Practices for Writing Comments in Python

Good comments can be the difference between a codebase that's easy to maintain and one that feels like deciphering ancient scripts. Follow these best practices to make your comments clear, useful, and professional.

1. Be Clear and Concise

Keep comments brief but informative. Avoid rambling or vague statements.

Good:

# Calculate the area of a circle using radius

area = 3.14 * radius ** 2

Bad:

# Here we do the calculation of the circle's area by multiplying pi with the square of the radius, which is necessary to find out how big the circle is in square units

2. Use Proper Grammar and Spelling

Comments are part of your code’s documentation—write them professionally. Mistakes can confuse readers and look careless.

3. Avoid Obvious Comments

Don’t state the obvious. Your code should speak for itself where possible.

# Increment i by 1

i += 1  # Avoid this comment; it’s redundant

4. Explain “Why,” Not “What”

Focus comments on why something is done rather than what is done. The code already shows the “what.”

5. Keep Comments Up to Date

Outdated comments are more harmful than none. Always update comments if you change the code.

6. Use Comments to Explain Complex Logic or Algorithms

If you’re implementing tricky logic or mathematical formulas, a comment can help explain the approach.

7. Use TODO Comments for Pending Work

If you need to revisit or improve a section, mark it clearly:

# TODO: Optimize this sorting algorithm for large datasets

8. Follow Consistent Comment Style

Stick to the same comment style throughout your codebase (for example, always starting with a capital letter and using punctuation).

Tip: Make Comments a Part of Your Coding Habit

Writing good comments isn’t an afterthought. Incorporate it naturally while coding, like Rajat does when he writes his college projects—because a little clarity goes a long way.

Want to learn more techniques that can help you write cleaner code? Start exploring Python identifiers to name your variables smartly and make your comments even more meaningful.

Real-Life Examples: Using Comments Like a Pro

Here, we’ll use simple, relatable scenarios with Indian names to illustrate how comments can clarify code.

Example 1: Calculating Student Grades

# Function to calculate grade based on marks
def calculate_grade(marks):
    # Check if marks are valid
    if marks < 0 or marks > 100:
        return "Invalid marks"
    # Assign grade based on marks
    if marks >= 90:
        return "A+"
    elif marks >= 75:
        return "A"
    elif marks >= 60:
        return "B"
    elif marks >= 50:
        return "C"
    else:
        return "Fail"
# Example usage:
grade = calculate_grade(82)  # For Sarita's exam score
print("Grade:", grade)

Output:

Grade: A

Explanation: Comments explain each step, from validating input to assigning grades. Sarita can easily understand how her marks translate into a grade.

Example 2: Monthly Expense Calculator

# Calculate total expenses for the month
def calculate_expenses(rent, groceries, utilities):
    # Sum all expense categories
    total = rent + groceries + utilities
    return total
# Priya’s expenses this month
total_expenses = calculate_expenses(12000, 5000, 3000)
print("Total Expenses:", total_expenses)

Output:

Total Expenses: 20000

Explanation: Simple, clear comments guide the reader through the purpose and logic of the function and variable usage.

Example 3: Disabling Code During Debugging

# Debug: Print intermediate results
# print("Calculating total expenses now...")
total_expenses = 15000 + 7000 + 2500
print("Expenses calculated.")

Output:

Expenses calculated.

Explanation: The debug print statement is temporarily disabled with a comment, allowing easy toggling during troubleshooting.

Tip: When you write comments like these, you’re not just explaining code—you’re telling a story. Your future self or teammates will thank you!

For better readability, especially in large projects, combining clean commenting with structured elements like Python keywords helps maintain clarity.

Conclusion

Comments in Python are your best allies for writing clear, maintainable, and professional code. From simple single-line comments to formal docstrings, each serves a unique purpose to improve code readability. Thoughtful comments help explain your intent, clarify complex logic, and make collaboration easier.

Remember, comments aren’t just for others—they’re for your future self, too. Keep them clear, concise, and relevant. Avoid cluttering code with obvious remarks, and always update comments as your code evolves. With these habits, your Python code will be as polished as a well-prepared exam answer!

FAQ’s

1. Do comments affect performance or output in Python?

No, comments do not affect the performance or output of a Python program. Python ignores comments during execution, so they serve only for code clarity without impacting runtime or memory usage.

2. Are comments in Python ignored during execution?

Yes, Python completely ignores comments during program execution. They are meant only for developers to understand the code better and have no effect on how the program runs or its results.

3. What are the common mistakes to avoid while using comments in Python?

Avoid writing obvious comments, outdated comments, and inconsistent styles. Over-commenting or unclear explanations can reduce readability. Always keep comments relevant, concise, and updated alongside code changes.

4. Where NOT to use comments in Python?

Avoid commenting on obvious code lines, like simple assignments or increments. Also, don’t clutter your code with excessive comments, as it can distract readers and reduce overall clarity.

5. What are single-line comments in Python?

Single-line comments start with a # symbol and continue to the end of the line. They explain specific lines or parts of code and improve readability without affecting program execution.

6. How to write multi-line comments in Python?

Use multiple single-line comments starting with # for multi-line comments. Alternatively, triple-quoted strings can be used, but they serve best as docstrings or documentation rather than comments.

7. What are docstrings in Python and how do they differ from comments?

Docstrings are triple-quoted strings placed below function, class, or module definitions. They document purpose and usage, accessible at runtime, unlike regular comments that are ignored during execution.

8. When should you use comments in Python?

Use comments to explain complex logic, clarify constants, summarize code sections, leave TODO notes, and temporarily disable code during debugging. They enhance maintainability and team collaboration.

9. Can comments be placed inline with code in Python?

Yes, inline comments are allowed after code on the same line. Use them sparingly to add brief explanations without overwhelming the line or reducing readability.

10. How can comments improve code maintainability?

Comments clarify purpose and logic, making it easier for developers to understand, debug, and update code. This reduces errors and speeds up future development and collaboration.

11. Are triple quotes recommended for writing multi-line comments?

Triple quotes are intended for docstrings but can mimic multi-line comments if not assigned to variables. However, it’s best practice to use # for actual comments for clarity and consistency.

12. Should comments explain ‘what’ or ‘why’ in code?

Focus comments on explaining why the code does something rather than what it does. The code itself shows what happens; comments add valuable context and reasoning.

13. How to handle outdated comments in Python code?

Always update or remove outdated comments during code changes. Incorrect comments can confuse developers and lead to mistakes, so keeping them accurate is crucial.

14. What is the best style for writing comments in Python?

Use clear, concise sentences starting with a capital letter and proper punctuation. Maintain consistency in formatting and language throughout the codebase.

15. Can comments be used to disable code temporarily?

Yes, commenting out code lines is a common debugging technique. It lets you test changes without deleting code permanently, making it easy to restore if needed.

image

Take our Free Quiz on Python

Answer quick questions and assess your Python knowledge

right-top-arrow
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Explore Our Free Software Tutorials

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918068792934

Disclaimer

1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.

2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.