Data types and variables
Operators
Modules and Packages
Conversion Programs
More Code Examples
Cheat Sheet

Comments in Python

Comments are an essential part of any programming language, and Python is no exception. They are used to explain code, making it more readable and maintainable for yourself and others who may read your code in the future. Comments are ignored by the Python interpreter, so they do not affect the execution of the code.

Types of Comments

Single-line Comments

Single-line comments in Python start with the hash character (#). Anything following the # on that line is considered a comment.

Example

# This is a single-line comment
print("Hello, world!")  # This is an inline comment

Multi-line Comments

Python does not have a specific syntax for multi-line comments. However, multi-line comments can be created using consecutive single-line comments or by using multi-line strings.

Consecutive Single-line Comments

# This is a multi-line comment
# that spans multiple lines.
# Each line starts with a hash character.

Multi-line Strings

Triple quotes (''' or """) can be used for multi-line strings, which can also serve as multi-line comments. Note that this is a workaround, as technically these are string literals, but they are often used in practice for multi-line comments.

"""
This is a multi-line comment
using triple double-quotes.
It spans multiple lines.
"""
'''
This is a multi-line comment
using triple single-quotes.
It spans multiple lines.
'''

Usage of Comments

Explaining Code

Comments are primarily used to explain what a particular block of code does, which is especially useful for complex or non-obvious logic.

# Calculate the factorial of a number
def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n-1)

Temporarily Disabling Code

Comments can be used to temporarily disable parts of the code during debugging or testing.

print("This will be printed")
# print("This will not be printed")

Documentation Strings (Docstrings)

While not exactly comments, docstrings are a special kind of string used to document modules, classes, and functions. They are written using triple quotes and can span multiple lines. Docstrings are accessible via the __doc__ attribute and are a standard way of providing documentation within the code.

def add(a, b):
    """
    This function adds two numbers.
    
    Parameters:
    a (int): The first number.
    b (int): The second number.
    
    Returns:
    int: The sum of a and b.
    """
    return a + b

# Accessing the docstring
print(add.__doc__)

Best Practices for Writing Comments

  1. Be Clear and Concise: Write comments that are easy to understand. Avoid unnecessary words.
  2. Keep Comments Up-to-date: Ensure comments are updated whenever the code changes.
  3. Avoid Obvious Comments: Do not comment on things that are self-explanatory.
  4. Use Comments to Explain Why, Not What: Explain the reasoning behind a block of code rather than just describing what the code does.

Example of Good Comments

# Load the configuration file
config = load_config("config.yaml")

# Loop through each item in the list
for item in items:
    process(item)

Example of Bad Comments

# This is a bad comment because it restates the code
x = x + 1  # Increment x by 1