Comments and Docstrings are lines of text in a computer program that explain code behavior to humans. They are ignored by the Python interpreter during execution.
Any text starting with the hash mark (#) on a line is treated as a comment. It can stand on its own line or at the end of a line of code.
# This is a comment on its own line
print("Hello, World!")
print("Welcome to Python!") # This is an inline commentPython does not have a specific syntax for multi-line comments. To write comments spanning multiple lines, you can use:
# This is a comment
# that spans across
# multiple lines.Since Python ignores string literals that are not assigned to a variable, you can use triple quotes (""" or ''') to write comments:
"""
This is a multi-line string
that acts as a comment because it
is not assigned to any variable.
"""
print("Hello, World!")- Important Note: Triple-quoted strings are technically string literals, not actual comments. Python compiles them into bytecode, which can introduce minor performance and memory overhead if placed inside functions.
Docstrings (Documentation Strings) are triple-quoted string literals placed immediately as the first statement inside a function, class, or module. Unlike comments, docstrings are preserved by Python and can be accessed dynamically at runtime using the __doc__ attribute or the built-in help() function.
def add(a, b):
"""
Returns the sum of a and b.
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__)