TOPIC 4: Functions & Code Documentation
Completion requirements
3. Documentation (Docstrings)
Docstrings are used to describe the functionality of a function, class, or module. They help other developers (or your future self) understand what the code does.
- Docstrings are enclosed in triple quotes ("""docstring""").
- The docstring should immediately follow the function header.
Example 1: Basic Docstring
def greet(name):
"""
This function greets the person with their name.
"""
print(f"Hello, {name}!")
greet("Alice")
Explanation:
- The function greet(name) includes a docstring explaining that the function greets a person by their name.
- Calling help(greet) will display the docstring, helping you understand what the function does.
Example 2: Detailed Docstring for a Function
A more detailed docstring can include information about the parameters and the return value of the function.
def add(a, b):
"""
This function adds two numbers a and b.
Parameters:
a (int): The first number.
b (int): The second number.
Returns:
int: The sum of a and b.
"""
return a + b
Explanation:
- The docstring explains the function’s purpose, its parameters, and its return value.
- This is particularly useful for understanding the function's input-output behavior.