In this tutorial, we are going to learn about “Python Docstrings” with some easy and cool examples.
Before going in-depth into this topic first let us see what actually a Docstring in Python mean:
Docstrings in Python:
In Python Documentation String usually called Docstring are the String Literals.
These are used for Documentation in Python that may be declared in class, function, methods, etc.
1. The docstring line must begin with a capital letter and end with a “.”
2. The first line in a Docstring must be a short description.
3. If there are more lines usually, we leave the second line blank, to separate the summary from other lines.
4. The next lines should be one or more paragraphs describing the target to be achieved by a function etc.
We usually use 3 double quotes (“”” ) or 3 single quotes (”’) to declare a Docstring.
Types of Docstrings in Python:
There are 2 types namely:
- Single line Docstring.
- Multi-line Docstring.
Single line Docstring:
These are usually completed in a single line i.e the starting and ending of the Docstring is in the same line.
#Single line Docstrings in Python def fun(a): '''Returns the number entered by the user.''' return a print (fun.__doc__)
Returns the number entered by the user.
These contain multiple lines i.e the starting and ending of the Docstring is in the different line.
def fun(a): """Describing the function Parameters: it accepts one parameter from the user. Returns: it returns an integer passed to the function. """ return a print(fun.__doc__)
Describing the function Parameters: it accepts one parameter from the user. Returns: it returns an integer passed to the function.
The following are the popular Docstring formats in Python:
- Sphinx Style.
- Google Style.
- Numpy Style.
Finally, I hope that this tutorial helped you in understanding the topic “Python Docstrings”.
You can also read:
Merge two files into one in Python