Code

Typed, Tested, Documented

Professional code tells readers what it expects, explains itself, and proves that it works. Here are all three habits in one small function:

def scale(value: float, factor: float = 2.0) -> float:
    """Multiply value by factor.

    >>> scale(3.0)
    6.0
    """
    return value * factor
  • Type hints (value: float, -> float) document the contract. Tools like mypy or pyright check them before your code runs.
  • A docstring explains the purpose, and its >>> examples double as doctests. doctest runs them and compares the output.
  • A unit test pins the behavior down, including the error cases:
class TestScale(unittest.TestCase):
    def test_default(self):
        self.assertEqual(scale(3.0), 6.0)

    def test_rejects_text(self):
        with self.assertRaises(TypeError):
            scale("3", "x")

Good tests fail when the code is wrong. The checker will run your tests against two broken versions of the function, and your tests must catch both.

Assignment

  1. Give average_fuel type hints: readings: list[float], returning float.
  2. Return the average rounded to 2 decimals. Raise ValueError("no readings") if the list is empty.
  3. Add a docstring with at least two passing doctest examples.
  4. Give TestAverageFuel at least two test methods. One must check the value and one must check the ValueError (assertRaises).