Comments in Python

Comments in Python are used to explain the code and make it more readable for others (or yourself). They are ignored by the Python interpreter during execution.


Why Are Comments Useful?

  1. Code Explanation: Helps explain the purpose of the code, especially for complex logic.
  2. Collaboration: Makes it easier for teams to understand each other’s work.
  3. Debugging: Allows developers to temporarily disable parts of the code without deleting them.
  4. Documentation: Serves as an inline guide for future reference.

Types of Comments in Python

Python supports two types of comments:

1. Single-Line Comments

Single-line comments start with a # and extend to the end of the line.

Example:

# This is a single-line comment
print("Hello, World!")  # This prints a greeting message

2. Multi-Line Comments

For longer explanations, multi-line comments are used. These are written inside triple quotes (''' or """). Though technically these are treated as strings and not true comments, they are often used as multi-line comments.

Example:

"""
This is a multi-line comment.
It can span multiple lines and is useful for
explaining complex code or providing documentation.
"""
print("Python is awesome!")

Tips for Writing Good Comments

  1. Be Clear and Concise: Write comments that explain the “why” behind the code, not the “what” (which is usually obvious from the code itself).

    • Not Recommended:
      x = 10  # Assign 10 to x
    • Recommended:
      x = 10  # Number of items to process
  2. Avoid Redundancy: Don’t state the obvious.

    # Loop through the list
    for item in items:
        print(item)  # Print each item
  3. Use Comments for Complex Logic:

    # Calculate the total cost after applying a 10% discount
    total_cost = price * quantity * 0.9
  4. Disable Code Temporarily: Comments can be used to debug by disabling parts of the code:

    # print("This line is disabled temporarily")

Docstrings: Special Multi-Line Comments

Python supports docstrings to provide documentation for modules, functions, and classes. These are written in triple quotes and are accessible via the help() function.

Example:

def greet(name):
    """
    This function greets the person whose name is provided.
    Arguments:
    name (str): The name of the person.
    """
    print(f"Hello, {name}!")

Accessing Docstrings:

print(greet.__doc__)

Output:

This function greets the person whose name is provided.
Arguments:
name (str): The name of the person.

Common Mistakes to Avoid

  1. Overusing Comments: Excessive comments can clutter the code.
  2. Outdated Comments: Always update comments when you modify the code.
  3. Using Comments for Version Control: Instead of leaving commented-out old code, use proper version control tools like Git.

Summary of Key Points

TypeSyntaxUse Case
Single-Line Comments#Brief explanations or disabling code.
Multi-Line Comments''' or """Longer explanations or documentation.
Docstrings''' or """Documenting functions, classes, or modules.

Try It Yourself

Problem 1: Add meaningful comments to the following code:

radius = 5
area = 3.14 * radius * radius
print(area)
Suggested Solution
# Define the radius of the circle
radius = 5
 
# Calculate the area using the formula π * r^2
area = 3.14 * radius * radius
 
# Print the calculated area
print(area)

Problem 2: Write a program to check whether a number is even or odd and add comments explaining your code.

Suggested Solution
# Input a number from the user
num = int(input("Enter a number: "))
 
# Check if the number is divisible by 2
if num % 2 == 0:
    # Print if the number is even
    print(f"{num} is even.")
else:
    # Print if the number is odd
    print(f"{num} is odd.")

Pyground

Play with Python!

Output: