Bird
Raised Fist0
Pythonprogramming~10 mins

Docstrings and documentation in Python - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - Docstrings and documentation
Define function
Add docstring inside triple quotes
Function body code
Call help() or __doc__ to read docstring
See documentation output
This flow shows how to write a docstring inside a function and then access it using help() or __doc__.
Execution Sample
Python
def greet(name):
    """Return a greeting message for the given name."""
    return f"Hello, {name}!"

print(greet.__doc__)
Defines a function with a docstring and prints the docstring.
Execution Table
StepActionEvaluationResult
1Define function greet with docstringStore function object with docstringFunction greet created with docstring
2Call greet.__doc__Access docstring attributeReturn a greeting message for the given name.
3Print docstringOutput string to consoleReturn a greeting message for the given name.
4EndNo more codeExecution stops
💡 All code executed, docstring printed, program ends
Variable Tracker
VariableStartAfter 1After 2Final
greetundefinedfunction object with docstringsamesame
greet.__doc__undefineddocstring stringsamesame
Key Moments - 3 Insights
Why do we use triple quotes for docstrings instead of single or double quotes?
Triple quotes allow the docstring to span multiple lines and are the standard for documentation strings, as shown in step 1 of the execution_table.
How do we access the docstring after defining the function?
We access it using the __doc__ attribute or the help() function, demonstrated in step 2 of the execution_table.
Does the docstring affect the function's behavior or output?
No, the docstring is only for documentation and does not change how the function runs, as seen in step 3 where only the docstring is printed.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of greet.__doc__ at step 2?
AReturn a greeting message for the given name.
BNone
C"Hello, {name}!"
DFunction object
💡 Hint
Check the 'Evaluation' column in row 2 of the execution_table.
At which step does the program print the docstring to the console?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look at the 'Action' and 'Result' columns in the execution_table.
If we remove the docstring, what would greet.__doc__ return?
AAn empty string ""
BNone
CAn error
DThe function code
💡 Hint
Recall that __doc__ is None if no docstring is provided.
Concept Snapshot
Docstrings are triple-quoted strings inside functions.
They describe what the function does.
Access them with function.__doc__ or help(function).
They do not affect function behavior.
Use them to make code easier to understand.
Full Transcript
This visual execution shows how to write and use docstrings in Python. First, we define a function with a triple-quoted string right after the function header. This string is the docstring and explains what the function does. The function body follows. When we access the function's __doc__ attribute, we get the docstring text. Printing this shows the documentation message. Docstrings help programmers understand code without changing how the code runs.

Practice

(1/5)
1. What is the main purpose of a docstring in Python?
easy
A. To store variable values
B. To execute code automatically
C. To explain what a function, class, or module does
D. To import external libraries

Solution

  1. Step 1: Understand what docstrings are

    Docstrings are special strings placed right after function, class, or module definitions to describe their purpose.
  2. Step 2: Identify the purpose of docstrings

    They help explain what the code does, making it easier for others and yourself to understand.
  3. Final Answer:

    To explain what a function, class, or module does -> Option C
  4. Quick Check:

    Docstrings = Explanation [OK]
Hint: Docstrings describe code purpose inside triple quotes [OK]
Common Mistakes:
  • Thinking docstrings run code
  • Confusing docstrings with comments
  • Using docstrings to store data
2. Which of the following is the correct way to write a docstring for a function in Python?
easy
A. def func(): // This is a docstring
B. def func(): # This is a docstring
C. def func(): "This is a comment"
D. def func(): '''This function does something'''

Solution

  1. Step 1: Identify correct docstring syntax

    Docstrings use triple quotes (''' or """) placed immediately after the function header.
  2. Step 2: Check each option

    def func(): '''This function does something''' uses triple single quotes right after the function header, which is correct. Options B and C use comments or double quotes incorrectly. def func(): // This is a docstring uses // which is not valid in Python.
  3. Final Answer:

    def func(): '''This function does something''' -> Option D
  4. Quick Check:

    Triple quotes after function = docstring [OK]
Hint: Docstrings use triple quotes right after function header [OK]
Common Mistakes:
  • Using # instead of triple quotes
  • Using single or double quotes only
  • Placing docstring before function header
3. What will be the output of the following code?
def greet():
    '''Return a greeting message.'''
    return "Hello!"

print(greet.__doc__)
medium
A. Return a greeting message.
B. None
C. Hello!
D. SyntaxError

Solution

  1. Step 1: Understand __doc__ attribute

    The __doc__ attribute of a function returns its docstring, which is the string inside triple quotes right after the function header.
  2. Step 2: Check the function's docstring

    The function greet has the docstring 'Return a greeting message.'. So, greet.__doc__ will output this string.
  3. Final Answer:

    Return a greeting message. -> Option A
  4. Quick Check:

    Function.__doc__ = docstring text [OK]
Hint: Use function.__doc__ to get its docstring text [OK]
Common Mistakes:
  • Expecting function return value instead of docstring
  • Confusing __doc__ with print output
  • Assuming __doc__ is None if no docstring
4. Identify the error in the following code snippet:
def add(a, b):
    """Add two numbers and return the result."""
    return a + b
medium
A. Docstring should use single quotes
B. Missing closing triple quotes for the docstring
C. Incorrect indentation of return statement
D. Function missing return statement

Solution

  1. Step 1: Check docstring syntax

    The docstring starts with triple double quotes """ but does not have a closing triple quote before the return statement.
  2. Step 2: Identify the error caused

    Without closing triple quotes, Python treats the return line as part of the string, causing a syntax error.
  3. Final Answer:

    Missing closing triple quotes for the docstring -> Option B
  4. Quick Check:

    Docstrings need opening and closing triple quotes [OK]
Hint: Always close triple quotes in docstrings [OK]
Common Mistakes:
  • Forgetting to close triple quotes
  • Indenting return inside docstring
  • Using single quotes inconsistently
5. You want to write a docstring for a function that calculates the area of a rectangle. Which of the following docstrings best follows good documentation practice?
hard
A. """Calculate the area of a rectangle given width and height. Parameters: width (float): The width of the rectangle. height (float): The height of the rectangle. Returns: float: The area of the rectangle."""
B. """Calculate area."""
C. """Area function"""
D. """Returns width * height"""

Solution

  1. Step 1: Understand good docstring content

    A good docstring clearly explains what the function does, its parameters, and what it returns.
  2. Step 2: Compare options

    """Calculate the area of a rectangle given width and height. Parameters: width (float): The width of the rectangle. height (float): The height of the rectangle. Returns: float: The area of the rectangle.""" provides a clear description, lists parameters with types, and explains the return value. Other options are too short or vague.
  3. Final Answer:

    """Calculate the area of a rectangle given width and height. Parameters: width (float): The width of the rectangle. height (float): The height of the rectangle. Returns: float: The area of the rectangle.""" -> Option A
  4. Quick Check:

    Good docstrings = clear + parameters + return [OK]
Hint: Include purpose, parameters, and return in docstrings [OK]
Common Mistakes:
  • Writing too short or vague docstrings
  • Not mentioning parameters or return values
  • Using incomplete sentences