Python Comments

In Python, comments are crucial for making your code more readable and understandable for others (or even yourself) when you come back to it after a while. Comments are lines in your code that the Python interpreter ignores during execution. They are often used to explain the purpose of specific lines of code, to provide context, or to leave notes for other developers who may be reading your code.

Why Use Comments?

Types of Comments in Python

Python supports two main types of comments:

Single-Line Comments

Single-line comments start with the # symbol. Everything after this symbol on the same line is ignored by the Python interpreter. Single-line comments are usually used for short explanations or notes.

Code Example


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

# Example of using single-line comments for explanation
x = 5  # Assigning value 5 to variable x
y = 10 # Assigning value 10 to variable y

# Performing addition
result = x + y
print("The sum is:", result)
                

Output

Hello, World! The sum is: 15

Multi-Line Comments

In Python, there is no specific syntax for multi-line comments like in some other programming languages. However, you can achieve multi-line comments in two ways:

Method 1: Using Multiple # Symbols

This method involves placing a # at the beginning of each line:

Code Example


# This is a multi-line comment
# explaining the code below.
x = 100
y = 200
print("Sum:", x + y)
                

Output

Sum: 300

Method 2: Using Triple Quotes

This method uses triple quotes, often used for docstrings but can serve as multi-line comments:

Code Example


"""
This is a multi-line comment
using triple quotes.
It spans multiple lines.
"""
print("Triple quotes example")
                

Output

Triple quotes example

Best Practices for Writing Comments

Docstrings in Python

Docstrings are another form of comment that Python uses for documenting modules, classes, and functions. These are written using triple quotes and are typically placed just below the definition of a function, class, or module.

Code Example


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

# Calling the function
greet("Alice")
                

Output

Hello, Alice!