Docstring
- Python course
- Beginner
- Lesson 73/116
- 3 min
Learn function documentation with """...""".
Docstring
A docstring is a triple-quoted string that describes what a function does. It goes on the first line of the body:
def add(a, b):
"""Add two numbers and return the result."""
return a + bThe docstring can be read with help(add) or add.__doc__. It explains how to use the function and makes teamwork easier.
Docstring conventions
A good docstring describes what the function does, its parameters and return value:
def divide(a, b):
"""Divide a by b.
Parameters:
a: dividend
b: divisor
Returns:
quotient (float)
"""
return a / bThis gives developers a chance to use the function correctly. IDEs show the docstring as a hint.
Practice Write a function with a docstring
Define a function called square that takes a parameter n. Put a docstring """Return the square of n.""" on the first line of the body. Return n * n. Assign square(5) to result. Then print print(result).
Starter code
# Define the square functionSample solution
def square(n):
"""Return the square of n."""
return n * n
result = square(5)
print(result)Expected output
25
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Where is a docstring written?
- Before the function name
- After the function call
- On the first line of the function body Correct answer
- After the return statement
Explanation: A docstring goes on the first line of the body.
2 Complete the docstring
def add(a, b):
____Add two numbers."""
return a + b
def add(a, b):
"""Add two numbers."""
return a + b
Explanation: A triple-quoted docstring explains the body.
3 Match the docstring parts
| Term | Meaning |
|---|---|
""" |
Triple quotes |
help() |
Shows docstring |
__doc__ |
Docstring attribute |
first line |
Docstring location |