GP106: Computing - 2024 Lab 5
GP106: Computing - 2024 Lab 5
University of Peradeniya
GP106: Computing - 2024
Lab 5 - Python Documentation and Testing
Overview
Python Docstrings
Python docstrings are documentation strings that are used to document Python modules, functions, classes,
or methods. They provide a way to describe the purpose, usage, and behavior of the code to other
developers or to your future self. Docstrings are enclosed in triple quotes (either single or double) and
placed immediately after the definition of a module, function, class, or method.
Module-level docstring: Place a docstring at the beginning of a Python file to describe the purpose
of the module.
Function docstring: Place a docstring immediately after the function definition to describe what
the function does, its parameters, return values, and any other relevant information.
Python Doctest
Python doctests are a way to test your code by including examples in the docstrings of your functions,
methods, or modules. These examples demonstrate how to use the code and what output to expect.
Doctests are executed automatically when you run the Python module using the doctest module, helping
to ensure that your code behaves as documented.
Include examples in docstrings: Write example inputs and expected outputs directly in the
docstrings of your functions, methods, or modules.
Run doctests: To run the doctests, use the doctest module's testmod() function. This function
automatically finds and executes doctests in the module.
Lab Exercises:
Rewrite the following code adhering to Python best practices. The given function is to calculate the area
of a circle with a random radius value when the minimum and maximum range of the radius is given.
a. Create your own Python module called “circlemodule” containing the following functions. Use
suitable function names and parameter names.
1. Create a function that takes two arguments radius and angle (in radians) and returns the
area of a circle sector.
2. Create a function that takes two arguments radius and angle (in radians) and returns the
arc length of a circle sector.
b. Documentation
1. Add a module-level docstring at the beginning of your Python module.
2. Add docstrings to each function you created. Docstrings should describe the purpose of
the function, its parameters, and its return value.
3. Test the docstrings by calling help(circlemodule) from another Python script.
a. Create a new function in the same module that takes two arguments radius and angle (in radians)
and returns the perimeter of a circle sector and add docstrings.
b. Inside the docstring, add at least two doctest cases for your function. Make sure to consider both
typical use cases and edge cases.
Submission Instructions