Docstrings in Python
A docstring (documentation string) in Python is a special kind of comment used to
explain
what a function, class, or module does. It is written inside """triple quotes"""
just below the function definition.
Docstrings are useful for documentation and can be accessed using the .__doc__
attribute.
Syntax:
def function_name(parameters):
"""This is a docstring.
It explains what the function does."""
# function body
...
Example: Using a docstring in a function
def add(a, b):
"""This function takes two numbers
and returns their sum."""
return a + b
print(add(4, 5))
print(add.__doc__)
Output:
9
This function takes two numbers
and returns their sum.
Explanation:
add(4, 5)returns 9.- When we call
add.__doc__, it prints the docstring written inside the function. - This is helpful for documentation and to tell other programmers (or yourself) what this function does.
Key Points about Docstrings:
- Written inside
"""triple quotes"""immediately after function definition. - Can be accessed at runtime using
function_name.__doc__. - Helps make the code self-documenting and easier to understand.
Summary:
- Docstrings are used to describe what a function or program does.
- They do not affect program execution but are very helpful for documentation.