Comments in Python are used to explain the purpose of code, make it more understandable, and improve its readability. They are ignored by the Python interpreter and are purely for human readers. Python supports both single-line and multi-line comments.
1. Single-Line Comments:
- Single-line comments begin with the
#
symbol and extend until the end of the line. - They are commonly used to add short explanations or clarifications within the code.
Example:
# This is a single-line comment x = 10 # Assigning the value 10 to the variable x
2. Multi-Line Comments:
- Multi-line comments are enclosed within triple single quotes (
'''
) or triple double quotes ("""
). - They are typically used for longer explanations, docstrings (documentation strings), or commenting out blocks of code.
Example:
''' This is a multi-line comment. It spans multiple lines. ''' x = 10 """ This is also a multi-line comment. It can be enclosed in triple single quotes or triple double quotes. """
3. Comments for Documentation (Docstrings):
- Docstrings are special comments used to provide documentation for functions, classes, modules, or packages.
- They are placed immediately after the definition of the function, class, or module, enclosed within triple quotes.
- Docstrings can be accessed using the
__doc__
attribute of the object.
Example:
def add(x, y): """ Function to add two numbers. Parameters: x (int): First number. y (int): Second number. Returns: int: Sum of x and y. """ return x + y print(add.__doc__) # Output: Function to add two numbers.... (docstring content)
0 Comments