
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.doctestruns 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
- Give
average_fueltype hints:readings: list[float], returningfloat. - Return the average rounded to 2 decimals. Raise
ValueError("no readings")if the list is empty. - Add a docstring with at least two passing doctest examples.
- Give
TestAverageFuelat least two test methods. One must check the value and one must check theValueError(assertRaises).
- Give
average_fueltype hints:readings: list[float], returningfloat. - Return the average rounded to 2 decimals. Raise
ValueError("no readings")if the list is empty. - Add a docstring with at least two passing doctest examples.
- Give
TestAverageFuelat least two test methods. One must check the value and one must check theValueError(assertRaises).
main.py Python sleeping
Press Run to try your code, then Check to test it.