To use doctest, simply import it and call its testmod() function at the bottom of your Python file containing the examples you want to test. This will run all the examples in your docstrings or tutorials and output any failures or errors encountered during testing. For example, let’s say we have a module called “example” that contains a function named factorial:
# This is the "example" module.
# This module contains a function named factorial() that calculates the factorial of a given number.
def factorial(n):
"""Return the factorial of n, an exact integer >= 0."""
# Import the math module to use its functions
import math
# Check if input is valid (i.e., greater than or equal to zero and not a decimal)
if not n >= 0:
raise ValueError("n must be >= 0") # Raise an error if input is not valid
if math.floor(n) != n:
raise ValueError("n must be exact integer") # Raise an error if input is not an exact integer
# Calculate factorial using for loop (for demonstration purposes only)
result = 1 # Initialize the result variable to 1
for i in range(1, int(n)+1): # Loop through numbers from 1 to n (inclusive)
result *= i # Multiply the result by the current number in the loop
return result # Return the final result
To test our code with doctest, we can add the following line at the bottom of our “example” file:
# Import the doctest module
import doctest
# Test the code within the "example" file using doctest
doctest.testmod()
This will run all the examples in our docstrings and output any failures or errors encountered during testing. In terms of relevance to student questions, doctests can be used as a tool for evaluating how well an educational system responds to real-world queries made by students during classes or tutoring sessions. By using pre-written examples in docstrings or tutorials, we can ensure that our code is competently responding to these kinds of questions and providing accurate answers.