What Are Comments In Python?

Python comments are lines that the interpreter completely ignores during execution. It is written only for human understanding, not for computers.

Comments make our code easier to read, understand, and maintain. Imagine that comments work as notes inside your code, explaining what’s happening in your particular code logic.

Why Use Comments in Python?

1) Improves Code Readability: When someone reads your code after a week, it can be difficult to remember what each line does. So, if we add short and clear comments, you make your code self-explanatory.

For example:

# Calculate the area of a rectangle
length = 10
width = 5
area = length * width
print("Area:", area)
  • Here, you can see that the comment tells the reader that the code calculates the area of a rectangle. Even a beginner can understand it without guessing.

2) Facilitates Collaboration: When you work on industries, multiple developers often work on the same codebase projects. So the well-written comments help everyone to understand the purpose and functionality of each section of code.

This method avoids confusion, for example:

# This function converts temperature from Celsius to Fahrenheit

def to_fahrenheit(celsius):
return (celsius * 9/5) + 32
  • When another developer reads this function, they instantly know its purpose.

3) Eases Debugging and Maintenance: When we revisit our code after some time or need to fix a bug, comments help us to quickly remind us of our thought process.

# Using round() to limit floating-point precision
# This avoids errors when comparing decimal values
result = round(3.14159, 2)
print(result)

4) Acts as Learning Notes: If you’re learning Python, adding comments helps you remember new concepts. It’s like creating a personal guide within your code that explains how different things work.

Example:

# range(5) generates numbers from 0 to 4 (not including 5)
for i in range(5):
print(i)
  • It means, when you return later, you will instantly understand how the range() function works without searching online again.

5) Makes Your Code Professional: Good developers always leave helpful comments. When others review your work, they can easily follow your logic, which increases trust and productivity in team environments.

Comments in Python Programming

Types of Comments in Python

Python supports three main types of comments, each can be used for a different purpose:

  1. Single-Line Comments
  2. Multi-Line Comments
  3. Docstring Comments

1. Single-Line Comments

Single-line comments start with the # symbol. Everything written after # on that line is completely ignored by Python when the program runs.

Syntax:

# This is a single-line comment
print("Hello, World!") # This comment explains the print statement

Explanation:

  • The first line is a standalone comment that helps describe what the code does.
  • The second line has an inline comment, meaning it appears on the same line as a statement.
  • This type of comment is perfect for quick explanations or short notes in your code.
# Store user's age and check if they are an adult
age = 18
if age >= 18:
print("You are an adult!") # Condition is true

2. Multi-Line Comments

Sometimes we need to explain a bigger block of code or write detailed notes. Python doesn’t have a special syntax like /* … */, but there are two easy ways to write multi-line comments.

Option 1: Multiple Single-Line Comments

# This program calculates the area of a rectangle
# It takes length and width as inputs
# and prints the final area

length = 5
width = 10
area = length * width
print("Area of Rectangle:", area)
  • It keeps your comments structured and easy to read, especially when you’re explaining steps in a longer program.

Option 2: Triple Quotes (“”” or ”’): Python provides another way to use triple quotes using “”” or ”’.

"""
This program demonstrates
the use of triple-quoted multi-line comments.
It prints a simple message.
"""
print("Welcome to Python!")

Important Note: Technically, this is a string, not a real comment. But it’s not stored or used; Python ignores it, so it works like a multi-line comment.

3. Docstring Comments

Docstrings (documentation strings) are a special type of comment so we can describe functions, classes, or modules. They’re written using triple quotes and placed immediately after the definition line.

Docstrings are part of the code’s documentation, which means you can access them programmatically using Python’s built-in help() function.

Syntax:

def greet(name):
"""
This function greets the user
whose name is passed as an argument.
"""
print("Hello,", name + "!")

Example:

def add_numbers(a, b):
"""
Adds two numbers and returns the result.

Parameters:
a (int or float): The first number
b (int or float): The second number

Returns:
int or float: The sum of a and b
"""
return a + b

# Access the docstring using help()
help(add_numbers)

Output of this program:

Help on function add_numbers in module __main__:

add_numbers(a, b)
Adds two numbers and returns the result.

Parameters:
a (int or float): The first number
b (int or float): The second number

Returns:
int or float: The sum of a and b

Essentials Points of Python Comments

a) Keep Comments Relevant: Always add value in your particular comments. Below, we describe the differences between good and bad comments.

(i) Bad Example:

x = 10  # Assigning 10 to x

(ii) Good Example:

x = 10  # Represents the base value for calculations

b) Use Docstrings for Functions and Classes: Always document the purpose of a function or class with a docstring.

c) Avoid Over-Commenting: Comments should not clutter the code. Write easy and meaningful comments.

d) Update Comments as Code Changes: Remember one thing, outdated comments can confuse readers, so keep them updated after any code changes.

e) Use Consistent Style: Follow a consistent commenting style across your whole project.

Examples of Using Comments in a Python Program

# Define a function to calculate the square of a number
def calculate_square(number):
"""
This function calculates the square of a given number.
It takes one argument:
- number: The number to be squared
"""
return number ** 2

# Use the function
result = calculate_square(5) # Square of 5 is 25
print("Square:", result)

Explanation of this code:

  • A single-line comment explains the function declaration.
  • A docstring describes the function’s purpose.
  • An inline comment clarifies the result variable.

Learn Advanced Topics About Python

Leave a Comment