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.
Single-line comments in Python start with the hash character (#
). Anything following the #
on that line is considered a comment.
# This is a single-line comment
print("Hello, world!") # This is an inline comment
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.
# This is a multi-line comment
# that spans multiple lines.
# Each line starts with a hash character.
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.
'''
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)
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")
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__)
# Load the configuration file
config = load_config("config.yaml")
# Loop through each item in the list
for item in items:
process(item)
# This is a bad comment because it restates the code
x = x + 1 # Increment x by 1