Inline Documentation with Triple Quotes
🏷️ Functions / Docstrings
When you write code, it's important to explain what your functions do. Inline documentation using triple quotes is Python's built-in way to attach helpful descriptions directly to your functions. These descriptions, called docstrings, make your code easier to understand for yourself and others.
🧠 What Are Docstrings?
A docstring is a string literal that appears right after the definition of a function, method, class, or module. It describes what the code does. Python uses triple quotes (""" or ''') to create these strings.
- Docstrings are stored as a special attribute called doc on the function.
- They are ignored by Python during execution but are incredibly useful for documentation tools and developers reading your code.
- Unlike regular comments (starting with #), docstrings can span multiple lines and are accessible programmatically.
⚙️ Basic Syntax for Function Docstrings
Place the docstring immediately after the function definition line, indented at the same level as the function body.
Structure: - Start with """ (or ''') - Write a brief summary on the first line - Add a blank line (optional but recommended for multi-line docstrings) - Provide more details, parameter descriptions, and return value info - Close with """
Example: A simple function with a docstring looks like this:
def greet(name): """Greet a person by name.""" print(f"Hello, {name}!")
The docstring here is: """Greet a person by name."""
🛠️ One-Line vs. Multi-Line Docstrings
| Feature | One-Line Docstring | Multi-Line Docstring |
|---|---|---|
| Length | Short, fits on one line | Longer, spans multiple lines |
| Usage | Simple functions with obvious behavior | Complex functions needing detailed explanation |
| Format | """Summary here.""" | """Summary line. |
| More details here. | ||
| """ | ||
| Example | def add(a, b): | def calculate_area(radius): |
| """Return the sum of a and b.""" | """Calculate the area of a circle. | |
| return a + b | Takes radius as input and returns area. | |
| """ | ||
| return 3.14 * radius * radius |
🕵️ How to View a Docstring
You can access a function's docstring in two ways:
- Using the help() function: help(function_name)
- Using the doc attribute: print(function_name.doc)
Example: If you have a function def multiply(x, y): with a docstring, you can view it by typing: - help(multiply) — shows the full documentation - print(multiply.doc) — prints just the docstring text
📝 Best Practices for Writing Docstrings
- Start with a capital letter and end with a period.
- Use the imperative mood (e.g., "Calculate" not "Calculates").
- Keep the summary line concise — under 80 characters if possible.
- For multi-line docstrings, include a blank line after the summary.
- Describe parameters and return values clearly.
Example of a well-written multi-line docstring:
def find_max(numbers): """Find the maximum value in a list of numbers.
**This function iterates through the list and returns**
**the largest number found.**
**Args:**
**numbers (list): A list of numeric values.**
**Returns:**
**int or float: The largest number in the list.**
**"""**
**return max(numbers)**
🎯 Why Docstrings Matter for Your Code
- Self-documenting code — Your functions explain themselves without needing separate documentation files.
- Team collaboration — Other engineers can understand your functions without reading every line of code.
- Tool support — IDEs and documentation generators (like Sphinx) use docstrings to create beautiful documentation automatically.
- Maintainability — When you revisit your code months later, docstrings remind you what each function does.
✅ Quick Checklist for Your Docstrings
- ✅ Is the docstring placed immediately after the function definition?
- ✅ Does it use triple quotes (""")?
- ✅ Does it start with a clear summary of what the function does?
- ✅ For complex functions, does it describe parameters and return values?
- ✅ Is the docstring accurate and up-to-date with the code?
By using triple quotes for inline documentation, you make your Python code more professional, readable, and maintainable. Start adding docstrings to every function you write — your future self (and your teammates) will thank you!
Triple-quoted strings placed immediately after a function definition create docstrings that document what the function does for other engineers reading the code.
📘 Example 1: Basic Function with Triple-Quoted Docstring
This example shows a simple docstring using triple double quotes right after the function header.
def add_numbers(a, b):
"""Return the sum of two numbers."""
return a + b
print(add_numbers(3, 5))
📤 Output: 8
📘 Example 2: Multi-Line Docstring with Triple Quotes
This example demonstrates a docstring that spans multiple lines for more detailed explanation.
def greet_user(name):
"""
Greet a user by name.
This function takes a name string and returns
a friendly greeting message.
"""
return f"Hello, {name}!"
print(greet_user("Alice"))
📤 Output: Hello, Alice!
📘 Example 3: Docstring with Parameter and Return Descriptions
This example shows how to document what each parameter does and what the function returns.
def calculate_area(length, width):
"""
Calculate the area of a rectangle.
Parameters:
length (float): The length of the rectangle.
width (float): The width of the rectangle.
Returns:
float: The area of the rectangle.
"""
return length * width
print(calculate_area(4.5, 3.0))
📤 Output: 13.5
📘 Example 4: Docstring Accessed via help() Function
This example shows how engineers can view a function's docstring using Python's built-in help function.
def convert_celsius_to_fahrenheit(celsius):
"""
Convert a temperature from Celsius to Fahrenheit.
Formula: (celsius * 9/5) + 32
"""
return (celsius * 9/5) + 32
help(convert_celsius_to_fahrenheit)
📤 Output: Help on function convert_celsius_to_fahrenheit in module main: convert_celsius_to_fahrenheit(celsius) Convert a temperature from Celsius to Fahrenheit. Formula: (celsius * 9/5) + 32
📘 Example 5: Docstring Stored in doc Attribute
This example demonstrates that docstrings are stored as the function's __doc__ attribute and can be printed directly.
def check_even(number):
"""Return True if the number is even, otherwise False."""
return number % 2 == 0
print(check_even.__doc__)
📤 Output: Return True if the number is even, otherwise False.
Comparison Table
| Feature | Triple-Quoted Docstring | Regular Comment (#) |
|---|---|---|
| Placement | First line after function definition | Anywhere in code |
| Accessible via code | Yes (using __doc__ or help()) |
No |
| Supports multi-line | Yes | No (each line needs #) |
| Used by documentation tools | Yes | No |
When you write code, it's important to explain what your functions do. Inline documentation using triple quotes is Python's built-in way to attach helpful descriptions directly to your functions. These descriptions, called docstrings, make your code easier to understand for yourself and others.
🧠 What Are Docstrings?
A docstring is a string literal that appears right after the definition of a function, method, class, or module. It describes what the code does. Python uses triple quotes (""" or ''') to create these strings.
- Docstrings are stored as a special attribute called doc on the function.
- They are ignored by Python during execution but are incredibly useful for documentation tools and developers reading your code.
- Unlike regular comments (starting with #), docstrings can span multiple lines and are accessible programmatically.
⚙️ Basic Syntax for Function Docstrings
Place the docstring immediately after the function definition line, indented at the same level as the function body.
Structure: - Start with """ (or ''') - Write a brief summary on the first line - Add a blank line (optional but recommended for multi-line docstrings) - Provide more details, parameter descriptions, and return value info - Close with """
Example: A simple function with a docstring looks like this:
def greet(name): """Greet a person by name.""" print(f"Hello, {name}!")
The docstring here is: """Greet a person by name."""
🛠️ One-Line vs. Multi-Line Docstrings
| Feature | One-Line Docstring | Multi-Line Docstring |
|---|---|---|
| Length | Short, fits on one line | Longer, spans multiple lines |
| Usage | Simple functions with obvious behavior | Complex functions needing detailed explanation |
| Format | """Summary here.""" | """Summary line. |
| More details here. | ||
| """ | ||
| Example | def add(a, b): | def calculate_area(radius): |
| """Return the sum of a and b.""" | """Calculate the area of a circle. | |
| return a + b | Takes radius as input and returns area. | |
| """ | ||
| return 3.14 * radius * radius |
🕵️ How to View a Docstring
You can access a function's docstring in two ways:
- Using the help() function: help(function_name)
- Using the doc attribute: print(function_name.doc)
Example: If you have a function def multiply(x, y): with a docstring, you can view it by typing: - help(multiply) — shows the full documentation - print(multiply.doc) — prints just the docstring text
📝 Best Practices for Writing Docstrings
- Start with a capital letter and end with a period.
- Use the imperative mood (e.g., "Calculate" not "Calculates").
- Keep the summary line concise — under 80 characters if possible.
- For multi-line docstrings, include a blank line after the summary.
- Describe parameters and return values clearly.
Example of a well-written multi-line docstring:
def find_max(numbers): """Find the maximum value in a list of numbers.
**This function iterates through the list and returns**
**the largest number found.**
**Args:**
**numbers (list): A list of numeric values.**
**Returns:**
**int or float: The largest number in the list.**
**"""**
**return max(numbers)**
🎯 Why Docstrings Matter for Your Code
- Self-documenting code — Your functions explain themselves without needing separate documentation files.
- Team collaboration — Other engineers can understand your functions without reading every line of code.
- Tool support — IDEs and documentation generators (like Sphinx) use docstrings to create beautiful documentation automatically.
- Maintainability — When you revisit your code months later, docstrings remind you what each function does.
✅ Quick Checklist for Your Docstrings
- ✅ Is the docstring placed immediately after the function definition?
- ✅ Does it use triple quotes (""")?
- ✅ Does it start with a clear summary of what the function does?
- ✅ For complex functions, does it describe parameters and return values?
- ✅ Is the docstring accurate and up-to-date with the code?
By using triple quotes for inline documentation, you make your Python code more professional, readable, and maintainable. Start adding docstrings to every function you write — your future self (and your teammates) will thank you!
Interactive Views
You are currently in 📚 All-in-One mode. Use the tabs at the top to switch to 📖 Theory Only or 💻 Code Only views.
Triple-quoted strings placed immediately after a function definition create docstrings that document what the function does for other engineers reading the code.
📘 Example 1: Basic Function with Triple-Quoted Docstring
This example shows a simple docstring using triple double quotes right after the function header.
def add_numbers(a, b):
"""Return the sum of two numbers."""
return a + b
print(add_numbers(3, 5))
📤 Output: 8
📘 Example 2: Multi-Line Docstring with Triple Quotes
This example demonstrates a docstring that spans multiple lines for more detailed explanation.
def greet_user(name):
"""
Greet a user by name.
This function takes a name string and returns
a friendly greeting message.
"""
return f"Hello, {name}!"
print(greet_user("Alice"))
📤 Output: Hello, Alice!
📘 Example 3: Docstring with Parameter and Return Descriptions
This example shows how to document what each parameter does and what the function returns.
def calculate_area(length, width):
"""
Calculate the area of a rectangle.
Parameters:
length (float): The length of the rectangle.
width (float): The width of the rectangle.
Returns:
float: The area of the rectangle.
"""
return length * width
print(calculate_area(4.5, 3.0))
📤 Output: 13.5
📘 Example 4: Docstring Accessed via help() Function
This example shows how engineers can view a function's docstring using Python's built-in help function.
def convert_celsius_to_fahrenheit(celsius):
"""
Convert a temperature from Celsius to Fahrenheit.
Formula: (celsius * 9/5) + 32
"""
return (celsius * 9/5) + 32
help(convert_celsius_to_fahrenheit)
📤 Output: Help on function convert_celsius_to_fahrenheit in module main: convert_celsius_to_fahrenheit(celsius) Convert a temperature from Celsius to Fahrenheit. Formula: (celsius * 9/5) + 32
📘 Example 5: Docstring Stored in doc Attribute
This example demonstrates that docstrings are stored as the function's __doc__ attribute and can be printed directly.
def check_even(number):
"""Return True if the number is even, otherwise False."""
return number % 2 == 0
print(check_even.__doc__)
📤 Output: Return True if the number is even, otherwise False.
Comparison Table
| Feature | Triple-Quoted Docstring | Regular Comment (#) |
|---|---|---|
| Placement | First line after function definition | Anywhere in code |
| Accessible via code | Yes (using __doc__ or help()) |
No |
| Supports multi-line | Yes | No (each line needs #) |
| Used by documentation tools | Yes | No |