Comments in Python are used to explain code and make it more readable. They are ignored by the interpreter when executing the program.

Single Line Comments

Single line comments start with a hash (#) symbol and continue until the end of the line.

  # This is a single line comment
print("Hello, World!")  # This comment follows a statement

Multi-line Comments

Python does not have a built-in syntax for multi-line comments like some other languages. However, multi-line strings or docstrings can be used as a workaround.

Using Multi-line Strings

Multi-line strings enclosed in triple quotes (""") or (''') can be used as comments. They are not ignored by the interpreter but can serve the purpose of commenting multiple lines.

This is a multi-line comment using
a multi-line string.
It spans across multiple lines.
print("This code will run")


Docstrings are similar to multi-line comments but are used to document functions, classes, or modules. They are enclosed in triple quotes and are stored as the __doc__ attribute of the function or class.

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

print(add(5, 3))  # Output: 8
print(add.__doc__)  # Output: This function adds two numbers.\n    Parameters:\n    a (int): The first number.\n    b (int): The second number.\n    Returns:\n    int: The sum of a and b.

Purpose of Comments

  • Explain Code: Describe what the code is doing in human-readable language.
  • Provide Context: Clarify complex or non-obvious sections of code.
  • Document Functionality: Detail the purpose and usage of functions, classes, or modules.
  • TODOs and Notes: Leave reminders or notes for future enhancements or improvements.

Comments are essential for maintaining code quality and readability. Use them effectively to enhance collaboration and understanding among developers.