For working professionals
For fresh graduates
More
13. Print In Python
15. Python for Loop
19. Break in Python
23. Float in Python
25. List in Python
27. Tuples in Python
29. Set in Python
53. Python Modules
57. Python Packages
59. Class in Python
61. Object in Python
73. JSON Python
79. Python Threading
84. Map in Python
85. Filter in Python
86. Eval in Python
96. Sort in Python
101. Datetime Python
103. 2D Array in Python
104. Abs in Python
105. Advantages of Python
107. Append in Python
110. Assert in Python
113. Bool in Python
115. chr in Python
118. Count in python
119. Counter in Python
121. Datetime in Python
122. Extend in Python
123. F-string in Python
125. Format in Python
131. Index in Python
132. Interface in Python
134. Isalpha in Python
136. Iterator in Python
137. Join in Python
140. Literals in Python
141. Matplotlib
144. Modulus in Python
147. OpenCV Python
149. ord in Python
150. Palindrome in Python
151. Pass in Python
156. Python Arrays
158. Python Frameworks
160. Python IDE
164. Python PIP
165. Python Seaborn
166. Python Slicing
168. Queue in Python
169. Replace in Python
173. Stack in Python
174. scikit-learn
175. Selenium with Python
176. Self in Python
177. Sleep in Python
179. Split in Python
184. Strip in Python
185. Subprocess in Python
186. Substring in Python
195. What is Pygame
197. XOR in Python
198. Yield in Python
199. Zip in Python
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!
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?
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.
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:
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.
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.
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.
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
# 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.
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.
# 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.
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.
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.
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.
Tip: Stick with # for actual commenting and use triple quotes only for documentation strings or placeholder comments in early development.
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.
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
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.
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.
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!
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
Always update or remove outdated comments during code changes. Incorrect comments can confuse developers and lead to mistakes, so keeping them accurate is crucial.
Use clear, concise sentences starting with a capital letter and proper punctuation. Maintain consistency in formatting and language throughout the codebase.
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.
Take our Free Quiz on Python
Answer quick questions and assess your Python knowledge
Author|900 articles published
Previous
Next
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918068792934
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.