๐Ÿ“ ๐Ÿ–‹๏ธ Python Commenting and Docstrings#

๐Ÿ“˜ What are Comments?#

Comments in Python are lines in the code that are not executed. They are meant for:

  • Explaining the purpose of the code

  • Making the code easier to read

  • Debugging purposes during development

Types of Comments:#

  1. Single-line comments: Start with #.

  2. Multi-line comments: Use triple quotes (''' or """).

# Single-line comment example
x = 10  # This is an inline comment explaining the variable

# Multi-line comment example
"""
This is a multi-line comment.
It spans multiple lines to explain the code below.
"""
y = 20
z = x + y

๐Ÿ“ What are Docstrings?#

Docstrings are special strings used to document a Python module, class, or function.

  • They describe what the code does, parameters, and return values.

  • Docstrings are defined using triple quotes (''' or """).

Example of a Docstring in a Function:#

def add_numbers(a, b):
    """
    Add two numbers and return the result.

    Parameters:
    a (int): First number
    b (int): Second number

    Returns:
    int: The sum of a and b
    """
    return a + b

๐Ÿ“š Accessing Docstrings in Jupyter Notebook#

You can view the docstring of a function, class, or module using:

  1. The help() function.

  2. The .__doc__ attribute.

Examples:#

# Accessing docstring using help()
help(add_numbers)

# Accessing docstring using __doc__
print(add_numbers.__doc__)
Help on function add_numbers in module __main__:

add_numbers(a, b)
    Add two numbers and return the result.
    
    Parameters:
    a (int): First number
    b (int): Second number
    
    Returns:
    int: The sum of a and b


    Add two numbers and return the result.

    Parameters:
    a (int): First number
    b (int): Second number

    Returns:
    int: The sum of a and b