Python Comments

Python allows you to enhance your code with several comments for different purposes. The most common ones include single-line comments, which start with a hash symbol (#), allowing you to add short explanations right next to a line of code. Multi-line comments are achieved using triple quotes (''' or """), which helps describe larger chunks of code. Lastly, docstrings, enclosed in triple quotes, are designed to document functions, classes, and modules, providing a structured way to explain their behavior and usage.

Python Comments
Table of Contents

Single-Line Comments

Adding explanations to your Python code with single-line comments is easy. These comments start with the hash symbol (#), and the computer won’t run anything you write after it on the same line.

  • The hash symbol (#) is the key – remember it!
  • The comment text can explain what the code is doing.

Example

# This variable stores the user's name
name = "Alice"
print("Hello,", name)

Explanation

  • Line 1: A comment explaining the purpose of the variable name.
  • Line 2: Creates a variable named name and assigns the value “Alice”.
  • Line 3: Prints a greeting using the name variable.

Multi-Line Comments

Unlike other languages, Python has no dedicated way to create multi-line comments. But there’s a clever trick! You can use triple quotes (either single or double) to create a block comment that spans multiple lines.

  • Wrap your comment between three single quotes (''') or three double quotes (""").
  • Python ignores everything inside these quotes, allowing you to write explanations over several lines.

Example

"""
This function calculates the area of a rectangle.
It takes the width and height as arguments and returns the calculated area.
"""

def calculate_area(width, height):
  area = width * height
  return area

Explanation

  • Line 1-4: A multi-line comment explaining the purpose and functionality of the calculate_area function.
  • Line 6: Defines the function with its name (calculate_area), parameters (width and height), and a colon (:).

Triple Single Quotes Example 

Triple single quotes (''') are another way to create multi-line strings in Python. While they function similarly to triple-double quotes ("""), they offer a specific advantage when you want to include double quotes within your string without needing to escape them.

  • Enclose your multi-line text between three single quotes (''').
  • This allows you to write text with double quotes without backslashes ().

Example

message = '''This is a message with "double quotes" inside 
and it won't cause any errors!'''

print(message)

Explanation

  • Lines 1-2: Assigns a multi-line string to the variable message using triple single quotes.
  • Notice the double quotes within the string “This is a message with “double quotes” inside”.
  • Line 4: Prints the content of the message variable. In this case, it will display the entire string, including the double quotes, exactly as written.

Triple Double Quotes Example 

Triple double quotes ("""), also known as triple quotes, are a powerful tool in Python for creating multi-line strings and docstrings.

  • Enclose your multi-line text between three double quotes (""").
  • This allows you to write text across multiple lines and include special characters like newlines (\n) without issues.

Example

poem = """Twinkle, twinkle, little star,
How I wonder what you are!
Up above the world so high,
Like a diamond in the sky.
"""

print(poem)

Explanation

  • Line 1-5: Assigns a multi-line string containing a poem to the variable poem using triple-double quotes.
    • Notice how the poem spans across multiple lines within the quotes.
  • Line 7: Prints the content of the poem variable, displaying the entire poem with its proper line breaks.

Docstrings

Python offers special docstring comments to add comprehensive documentation directly within your code. These comments, typically written using triple double quotes ("""), provide a way to explain a function, class, or module’s purpose, usage, and even details like arguments and return values.

  • Docstrings are enclosed between triple double quotes (""").
  • They appear below the definition of a function, class, or module.
  • Good practice involves following a clear structure to enhance readability.

Example

def greet(name):
  """
  This function greets the user by name.

  Args:
      name: The name of the person to greet (str).

  Returns:
      A string containing the greeting message.
  """
  message = "Hello, " + name + "!"
  return message

print(greet("Alice"))

Explanation

  • Line 1: Defines a function named greet that takes a parameter name.
  • Lines 2-10 are the docstring explaining the function’s purpose (greeting someone), what it takes (name as a string), and what it returns (a greeting message).
  • Lines 11-14 create a message string and then call the greet function with “Alice” as the argument.

Effective Commenting Strategies

Python provides a rich commenting system to enhance code readability and maintainability. These comments can be broadly categorized into several distinct types, each serving a specific purpose. Understanding these different types of comments and using them effectively is essential for writing clean, well-structured, and collaborative Python code.

Explanatory Comments: Clarifying Code Logic

Effective comments in Python go beyond just mentioning what the code does. Descriptive comments aim to explain the “why” behind the code’s logic, making it easier to understand the reasoning and intent.

  • Focus on explaining the purpose and thought process behind the code.
  • Use clear and concise language for better readability.

Example

# Check if the user input is a valid integer between 1 and 10
user_input = int(input("Enter a number between 1 and 10: "))
if 1 <= user_input <= 10:
  print("Valid input!")
else:
  print("Please enter a number between 1 and 10.")

Explanation

  • Line 1: The comment clarifies the purpose of the input validation (# Check if the user input is a valid integer between 1 and 10).
  • Line 2: Prompts the user for input and converts it to an integer.
  • Lines 3-6: Use an if statement to check if the input (user_input) is within the specified range (1 to 10).

Inline Comments: Adding Context Within Lines

Unlike some other languages, Python doesn’t have a dedicated way to write comments directly within a line of code. However, following the actual code, you can achieve a similar effect using short comments at the end of a line. These comments, often called inline comments, help add brief explanations or reminders next to the code they relate to.

  • Inline comments typically start with a hash symbol (#) followed by a space.
  • The comment text explains the code on the same line.

Example

name = "Bob"  # Assign the name "Bob"
greeting = "Hello, " + name  # Create a greeting message
print(greeting)  # Print the greeting

Explanation

  • Line 1: Assigns the string “Bob” to the variable name.
  • An inline comment (# Assign the name “Bob”) clarifies the purpose of this line.
  • Line 2: Concatenates “Hello, “ with the value of name and stores it in greeting. An inline comment explains this step.
  • Line 3: Prints the content of greeting, and another inline comment clarifies this action.

Documenting Functions and Methods

In Python, functions and methods, essentially reusable code blocks, can be enriched with comments to improve readability and understanding. These comments, typically docstrings, provide valuable information about the function’s purpose, usage, and even details like accepted arguments and returned values.

  • Docstrings are written using triple-double quotes ("""), placed right below the function definition.
  • They follow a clear structure to enhance readability, often including a summary, parameters, and return values.

Example

def calculate_area(width, height):
  """
  This function calculates the area of a rectangle.

  Args:
      width: The width of the rectangle (float).
      height: The height of the rectangle (float).

  Returns:
      The calculated area of the rectangle (float).
  """
  area = width * height
  return area

# Example usage:
rectangle_area = calculate_area(5.5, 3.2)
print(f"The area of the rectangle is {rectangle_area:.2f}")

Explanation

  • Line 1: Defines a function named calculate_area that takes two arguments, width and height.
  • Lines 2-11: Are the docstring explaining the function’s purpose (area calculation), the parameters it accepts (width and height as floats), and what it returns (the area as a float).
  • Line 16: Demonstrate how to call the function with specific values and store the result in rectangle_area.
  • Line 17: Prints the calculated area with two decimal places.

Commenting Classes

Classes in Python, such as blueprints for creating objects, benefit from clear comments like functions. These comments, often also written as docstrings, provide a high-level overview of the class’s purpose, its functionalities (methods), and sometimes even how to use it.

  • Docstrings for classes are similar to functions and use triple-double quotes (""").
  • They are placed right below the class definition line.

Example

class Point:
  """
  This class represents a point in two-dimensional space.

  Attributes:
      x: The x-coordinate of the point (float).
      y: The y-coordinate of the point (float).
  """

  def __init__(self, x, y):
      """
      Initializes a new Point object.

      Args:
          x: The x-coordinate of the point (float).
          y: The y-coordinate of the point (float).
      """
      self.x = x
      self.y = y

  # ... other methods of the Point class

# Example usage:
point1 = Point(3.1, 4.2)
print(f"Point coordinates: ({point1.x}, {point1.y})")

Explanation

  • Line 1: Defines a class named Point.
  • Lines 2-8: Are the docstring explaining the class’s purpose (representing a 2D point) and its attributes (x and y coordinates).
  • Lines 10-19: Define a special method called __init__, which initializes a new Point object. It takes two arguments (x and y) for the coordinates.
  • Lines 24-25: Show an example of creating a Point object and then printing its coordinates using the x and y attributes.

Code Readability: Python Commenting Best Practices

Effective commenting in Python is key to writing clean and understandable code. Here are some best practices to follow:

  • Focus on clarity and purpose
    Comments should explain the “why” behind your code, not just what it does. Use clear and concise language for better readability.
  • Use descriptive names
    Well-named variables and functions can often reduce the need for extensive comments.
  • Comment complex logic
    Provide comments for intricate parts of your code to break down the thought process and steps involved.
  • Avoid unnecessary comments
    Don’t explain the obvious code. Comments should clarify non-obvious sections or the reasoning behind the code.

Example

# Calculate the average of two exam grades, considering a passing grade is 70 or higher
def calculate_average(grade1, grade2):
  """
  This function calculates the average of two exam grades and indicates if the average is passing.

  Args:
      grade1: The first exam grade (integer).
      grade2: The second exam grade (integer).

  Returns:
      A tuple containing the average grade (float) and a message indicating if it's passing (string).
  """
  average = (grade1 + grade2) / 2
  passing_message = "Passing" if average >= 70 else "Failing"
  return average, passing_message

exam1_grade = 85
exam2_grade = 72

average, result = calculate_average(exam1_grade, exam2_grade)

print(f"The average grade is {average:.2f}. Overall result: {result}")

Explanation

  • Lines 3-12: The comment for calculate_average explains its purpose and what it returns (average and passing status).
    • Within the function, comments clarify the logic (# Calculate the average) and how the passing message is determined.
    • Notice how the variable names (exam_grade, average) are descriptive, reducing the need for further comments in those lines.

Python Commenting Pitfalls to Avoid

While comments can significantly improve your code in Python, there are also some practices to avoid for effective commenting. Here are a few:

  • Over-commenting
    Don’t explain every single line of code, especially if it’s straightforward. Comments should focus on clarifying complex logic or the reasoning behind the code.
  • Unnecessary comments
    Comments that simply restate what the code is already doing are redundant and can clutter your codebase.
  • Outdated comments
    If your code logic changes, but the comments don’t reflect those changes, they become misleading and can confuse you.
  • Unclear or poorly written comments
    Comments should be easy to understand. Avoid jargon and use concise language that explains the code’s intent.

Here’s an example of bad commenting

# This function adds two numbers (redundant comment)
def add_numbers(x, y):
  sum = x + y  # Explains what the code already does (unnecessary comment)
  return sum

result = add_numbers(5, 3)
print("The sum is:", result)

Explanation

  • The comment for add_numbers simply repeats what the function name already implies.
  • The comment within the function explains a basic arithmetic operation, which is unnecessary.