Docstrings in Python. Topic – 20

The Docstring In Python

Docstrings in Python are string literals that appear right after the definition of a function, method, class, or module. They are used to provide documentation for the code, explaining the purpose and functionality of the defined entity.

Python
def square(n):
    '''Takes in a number n, returns the square of n'''
    print(n**2)
square(5)
Python

In this example:

  • – `”’Takes in a number n, returns the square of n”’` is a docstring.
  • Docstrings are not displayed in the output when the function is called (`square(5)`).
  • The output is `25`, which is the result of the square function.
  • Here’s another example with more details:
def add(num1, num2):
    """
    Add up two integer numbers.

    This function simply wraps the ``+`` operator and does not
    do anything interesting, except for illustrating what
    the docstring of a very simple function looks like.

    Parameters
    ----------
    num1 : int
        First number to add.
    num2 : int
        Second number to add.

    Returns
    -------
    int
        The sum of ``num1`` and ``num2``.

    See Also
    --------
    subtract : Subtract one integer from another.

    Examples
    --------
    >>> add(2, 2)
    4
    >>> add(25, 0)
    25
    >>> add(10, -10)
    0
    """
    return num1 + num2
Python
  • This docstring provides information about the function, including parameters, return value, and examples of usage.
  • It helps other programmers (or yourself) understand how to use the `add` function.

Python Comments vs. Docstrings:

  • Comments are descriptions that help programmers understand the code. They are ignored by the Python interpreter.
  • Docstrings are used to document code, especially functions and methods. They are accessible using the `__doc__` attribute.

def square(n):
    '''Takes in a number n, returns the square of n'''
    return n**2

print(square.__doc__)
Python

The Output Of This Code Will Be:

Output
Takes in a number n, returns the square of n
Python

If you don’t know the “Formatted String in Python” just click on Read More.

I hope you understand “Docstrings in Python”  Need guidance or have questions? Drop a comment below. Share your email for a personalized touch—I’ll send exclusive resources and answer queries. Let’s code together, creating efficient code and memorable learning moments! 🚀

Finite number of  lines code and infinite possibilities

Programmer, Arpan Bera

Leave a Reply

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

ABOUT ME
Arpan Bera

Coding is like Love – everyone can start, but only a few finish without errors

Keep Updated to our News and Blog