Python Comments

In Python, comments are used to explain code, clarify its purpose, or leave notes for other developers (or yourself). Python ignores comments during execution, so they have no effect on the program itself.

There are two main types of comments in Python:

1. Single-Line Comments

A single-line comment starts with the # symbol. Everything after the # on that line is treated as a comment.

# This is a single-line comment
print("Hello, World!")  # This is an inline comment
  • You can place a comment on its own line or at the end of a line of code.
  • Good practice: Keep comments concise and relevant. Too many unnecessary comments can clutter the code.

2. Multi-Line Comments

Python doesn’t have a specific syntax for multi-line comments, but you can use consecutive # symbols on each line to create multiple single-line comments.

# This is a multi-line comment
# It spans multiple lines
# to explain what the code below does
print("Hello, Python!")

Alternatively, you can use triple-quoted strings (''' or """) as multi-line comments, but this is more commonly used for docstrings (which I’ll explain below). These triple-quoted strings are technically string literals, but if they are not assigned to a variable, Python will ignore them, so they behave like comments.

'''
This is a multi-line comment
spanning multiple lines.
'''
print("Hello, Python!")

3. Docstrings

Docstrings (documentation strings) are a special type of comment used to document functions, classes, and modules. They are written inside triple quotes (''' or """) and placed immediately after the definition of a function, class, or module.

def greet(name):
    """
    This function takes a name as input
    and prints a greeting message.
    """
    print(f"Hello, {name}!")
  • Docstrings are used for documentation purposes, and they can be accessed at runtime using the __doc__ attribute of the function or class.
print(greet.__doc__)

Key Points:

  • Use # for single-line comments.
  • Use consecutive # symbols for multi-line comments.
  • Use triple quotes (''' or """) for docstrings or multi-line comments, though docstrings are specifically meant for documentation.
Leave a Reply 0

Your email address will not be published. Required fields are marked *