Skip to main content

Python Comments

Introduction

Comments are explanatory text that you add to your code but are ignored by the Python interpreter. They are meant for humans to read, not for computers to execute. Adding comments to your code is a crucial programming practice as it helps other developers (and your future self) understand what your code does, why certain decisions were made, and how different parts work together.

In this tutorial, you'll learn:

  • What comments are and why they're important
  • How to write single-line comments
  • How to create multi-line comments
  • Best practices for writing effective comments

Why Use Comments?

Before diving into the syntax, let's understand why comments are so important:

  • Code Documentation: Comments explain what your code does, making it easier for others to understand.
  • Future Reference: They help you remember why you wrote code in a specific way when you revisit it later.
  • Debugging Aid: Comments can be used to temporarily disable code during debugging.
  • Code Planning: Before writing actual code, comments can outline the structure and logic.

Single-Line Comments in Python

In Python, you can create a single-line comment by using the hash symbol (#). Anything following the # until the end of the line is considered a comment and is ignored during execution.

python
# This is a single-line comment
print("Hello, World!") # This is also a comment, after some code

Output:

Hello, World!

Notice that only the print("Hello, World!") part was executed, while both comments were ignored by the Python interpreter.

Examples of Single-Line Comments

Here are more examples showing how single-line comments can be used:

python
# This program calculates the area of a rectangle
length = 10 # Length in meters
width = 5 # Width in meters

# Calculate the area
area = length * width

# Display the result
print(f"The area of the rectangle is {area} square meters")

Output:

The area of the rectangle is 50 square meters

Multi-Line Comments in Python

Python doesn't have a specific syntax for multi-line comments like some other programming languages do. However, there are two common ways to create multi-line comments:

1. Using Multiple Single-Line Comments

You can simply use the # symbol at the beginning of each line:

python
# This is a multi-line comment
# spanning multiple lines
# using multiple hash symbols
print("Hello from multi-line comments")

Output:

Hello from multi-line comments

2. Using Triple Quotes (Docstrings)

Although technically not comments but strings, triple quotes (""" or ''') are often used for multi-line comments, especially when writing documentation for functions, classes, or modules:

python
"""
This is a multi-line comment or docstring.
It can span multiple lines.
Python doesn't execute these strings unless they're assigned to a variable,
so they effectively work like comments.
"""
print("Hello from triple quotes")

'''
This is also a multi-line comment using single quotes.
It works the same way as the double-quoted version.
'''

Output:

Hello from triple quotes

When used at the beginning of a function, class, or module, these triple-quoted strings become docstrings, which are accessible through the __doc__ attribute and are used by documentation tools.

Using Comments for Documentation

One of the most common uses of comments is for documenting functions. Here's an example of how to properly document a function using docstrings:

python
def calculate_circle_area(radius):
"""
Calculate the area of a circle.

Parameters:
radius (float): The radius of the circle in units.

Returns:
float: The area of the circle in square units.
"""
import math
return math.pi * (radius ** 2)

# Using the function
area = calculate_circle_area(5)
print(f"The area of the circle is {area:.2f} square units")

# Accessing the function's docstring
print("\nFunction documentation:")
print(calculate_circle_area.__doc__)

Output:

The area of the circle is 78.54 square units

Function documentation:
Calculate the area of a circle.

Parameters:
radius (float): The radius of the circle in units.

Returns:
float: The area of the circle in square units.

Comments for Debugging

Comments can be used to temporarily disable code during debugging:

python
def divide(a, b):
# Check if b is zero
if b == 0:
return "Cannot divide by zero"
return a / b

# Test the function
print(divide(10, 2))
print(divide(10, 0))

# Debug the function
# print("Debug information:")
# print(f"Division function source code: {inspect.getsource(divide)}")

Output:

5.0
Cannot divide by zero

In this example, the last two lines are commented out, so they don't execute. This is a common technique during debugging when you want to temporarily disable some code without deleting it.

Best Practices for Writing Comments

Writing effective comments is an art. Here are some best practices:

  1. Be Clear and Concise: Write comments that are easy to understand but not unnecessarily verbose.

  2. Comment "Why" Not "What": The code already shows what is being done; comments should explain why it's being done that way.

    python
    # Bad comment - states the obvious
    x = x + 1 # Adding 1 to x

    # Good comment - explains the reason
    x = x + 1 # Adjust for zero-based indexing
  3. Keep Comments Updated: Outdated comments can be misleading and more harmful than no comments.

  4. Use Comments to Organize Code:

    python
    # === User Authentication ===
    username = input("Enter username: ")
    password = input("Enter password: ")

    # === Data Processing ===
    data = load_data(username)
    processed_data = process(data)
  5. Don't Comment Obvious Code: Comment only what needs explanation.

    python
    # Unnecessary comment
    counter = 0 # Initialize counter to zero

    # Necessary comment
    x = y * 1.8 + 32 # Convert from Celsius to Fahrenheit
  6. Use Block Comments for Complex Logic: Before writing a complex algorithm, explain your approach.

Real-World Example: Data Analysis Script

Let's see how comments can be used effectively in a more realistic script:

python
# Import required libraries
import pandas as pd
import matplotlib.pyplot as plt

def analyze_sales_data(file_path):
"""
Analyze the sales data from a CSV file and generate a summary report.

Parameters:
file_path (str): Path to the CSV file containing sales data

Returns:
dict: Summary statistics of the sales data
"""
# Load the data from CSV file
try:
data = pd.read_csv(file_path)
except FileNotFoundError:
return {"error": "File not found"}

# Data cleaning - remove missing values
data = data.dropna(subset=['sales_amount'])

# Calculate key metrics
total_sales = data['sales_amount'].sum()
average_sale = data['sales_amount'].mean()

# Group data by product category
# This helps us understand which categories perform best
category_sales = data.groupby('category')['sales_amount'].sum()

# Prepare the return dictionary with all calculated metrics
return {
"total_sales": total_sales,
"average_sale": average_sale,
"category_sales": category_sales,
"data_shape": data.shape
}

# Example usage
# results = analyze_sales_data("sales_2023.csv")
# print(f"Total sales: ${results['total_sales']:,.2f}")
# print(f"Average sale: ${results['average_sale']:.2f}")

In this example, comments help to:

  • Describe the purpose of the script at the top
  • Document the function with a docstring
  • Explain each section of the code
  • Provide context for why certain operations are performed
  • Include example usage (commented out)

Summary

Comments are a vital part of writing maintainable and readable code. In Python, you can use:

  • Single-line comments with the # symbol
  • Multi-line comments by using multiple # symbols or triple quotes

Remember that good comments explain the "why" behind your code rather than just restating what the code does. They should add value by providing context, explanations for complex logic, or documentation for others (and your future self).

While comments are important, aim to write self-documenting code by using descriptive variable names and clear code structure, using comments to supplement rather than compensate for unclear code.

Exercises

  1. Add appropriate comments to a previous Python program you've written.
  2. Write a function with proper docstring documentation that converts temperatures between Celsius and Fahrenheit.
  3. Review some open-source Python code on GitHub and observe how experienced developers use comments.
  4. Practice writing comments that explain "why" instead of "what" for a piece of complex code.

Additional Resources

Happy coding, and remember: code is read much more often than it's written, so invest time in good comments!



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)