Introduction
Python comments are non-executable lines of text that are ignored by the Python interpreter. They are used to provide explanations, notes, reminders, and documentation within the source code. Comments make code more readable and easier to maintain, especially when working in teams or revisiting code after a long period.
Imagine looking at a complex Python program written months ago without any explanations. Understanding the purpose of each section could become difficult. Proper comments help developers quickly understand the code and reduce confusion.
What are Python Comments?
Python comments are lines of text written within a Python program that are ignored during execution. They are intended for humans rather than computers.
Since comments are ignored by the Python interpreter, they do not affect the program’s output.
For example:
# This is a comment
print("Hello World")
Output:
The comment is ignored, and only the print() statement executes.
Why Use Comments?
Comments play an important role in software development.
- Improve code readability
- Help beginners understand code
- Make debugging easier
- Assist team collaboration
- Explain business logic
- Reduce maintenance effort
Well-commented code is easier to understand than code without explanations.
Python Comment Syntax
Python uses the hash (#) symbol to create comments.
Syntax
# Comment text
Anything written after # on the same line is treated as a comment.
Example:
# Display a welcome message
print("Welcome to Python")
Output:
Single-Line Comments
Single-line comments are the most common type of comments in Python.
Example:
# Store user name
name = "John"
# Display user name
print(name)
Output:
Each comment explains the purpose of the code that follows.
Inline Comments
Inline comments are written on the same line as a Python statement.
Example:
age = 18 # User age
print(age)
Output:
Inline comments can be useful for short explanations.
However, excessive inline comments can make code difficult to read.
Multi-Line Comments
Python does not have a dedicated syntax for multi-line comments like some programming languages.
Instead, developers typically use multiple single-line comments.
Example:
# This program calculates
# the total price of products
# including tax.
Triple Quotes as Multi-Line Comments
Triple quotes can also be used to create multi-line text blocks.
Example:
"""
This is a multi-line comment.
It explains the purpose
of the program.
"""
print("Python")
Output:
Although triple quotes create string literals rather than true comments, they are commonly used for documentation purposes.
Comments in Functions
Comments are often used to explain functions.
Example:
def add_numbers(a, b):
# Return sum of two numbers
return a + b
print(add_numbers(10, 20))
Output:
Comments in Loops
Comments can describe loop operations.
Example:
# Print numbers from 1 to 5
for i in range(1, 6):
print(i)
Output:
2
3
4
5
Comments in Conditional Statements
Example:
age = 20
# Check voting eligibility
if age >= 18:
print("Eligible to vote")
Output:
The comment clarifies why the condition exists.
Using Comments for Debugging
Developers often comment out code temporarily during testing.
Example:
name = "John"
# print("Debug:", name)
print("Program executed")
Output:
The commented line is ignored during execution.
This technique helps isolate problems during debugging.
Documentation Strings (Docstrings)
Python provides a special type of documentation called a docstring.
Docstrings are enclosed in triple quotes and placed immediately after a function, class, or module definition.
Example:
def greet():
"""
This function displays
a welcome message.
"""
print("Hello")
greet()
Output:
Real-Life Example
Suppose a company develops a payroll system.
Without comments:
salary = 50000
bonus = 5000
total = salary + bonus
print(total)
A new developer may not immediately understand the purpose of each variable.
With comments:
# Employee monthly salary
salary = 50000
# Annual performance bonus
bonus = 5000
# Calculate total earnings
total = salary + bonus
print(total)
Output:
The comments make the code much easier to understand.
Best Practices for Writing Comments
1. Keep Comments Clear
Write simple and meaningful comments.
Good:
# Calculate total salary
Bad:
# This line performs an operation
2. Avoid Obvious Comments
Bad:
# Assign 10 to x
x = 10
The code already explains itself.
3. Update Comments Regularly
If code changes, update related comments.
Outdated comments can cause confusion.
4. Use Comments for Complex Logic
Comments are most useful when explaining non-obvious code.
Example:
# Apply discount only for premium customers
5. Use Docstrings for Functions
Professional Python developers often use docstrings instead of excessive comments.
Example:
def calculate_tax():
"""
Calculates tax based on income.
"""
Common Mistakes
1. Writing Too Many Comments
Bad:
# Store value 10
x = 10
# Store value 20
y = 20
The code is already self-explanatory.
2. Writing Outdated Comments
Incorrect:
# Calculate total salary
total = salary - bonus
The comment no longer matches the code.
3. Using Comments Instead of Clear Variable Names
Bad:
# Customer age
x = 25
Better:
customer_age = 25
4. Forgetting the Hash Symbol
Incorrect:
This is a comment
Python generates an error.
Correct:
# This is a comment
5. Commenting Important Code Accidentally
Incorrect:
# print("Payment Successful")
The statement never executes.
Always review commented code carefully.
Conclusion
Python comments are an essential part of writing clean, maintainable, and professional code. They allow developers to explain logic, document functionality, leave notes, and improve collaboration among team members. Whether you are working on a small script or a large enterprise application, comments help make your code easier to understand and maintain.
Python supports single-line comments using the # symbol and documentation through docstrings. By following best practices and avoiding unnecessary or outdated comments, developers can create code that is both efficient and easy to read.
Python Comments – Interview Questions
Q 1: What are comments in Python?
Q 2: How do you write a single-line comment in Python?
Q 3: Does Python support multi-line comments?
Q 4: Why are comments important?
Q 5: Are comments executed in Python?
Python Comments – Objective Questions (MCQs)
Q1. Which symbol is used to write a single-line comment in Python?
Q2. How do you write a multi-line comment in Python?
Q3. What happens when you put a # symbol before a line of code in Python?
Q4. Which of the following is a valid comment in Python?
Q5. What is the main purpose of comments in Python code?