Learn AI/Python
LESSON 06 / 36Beginner 30 min with practice

Functions, validation, and useful tests

Turn a transformation into a small contract you can check.

WHAT YOU WILL LEARN
  • Write a pure function
  • Validate input assumptions
  • Test ordinary and edge cases

A function has a contract

A useful function says what it accepts, what it returns, and what it rejects. Pure functions depend only on their inputs and avoid changing outside state. They are especially helpful for preprocessing and metrics because the same inputs should yield the same outputs.

Validate assumptions where they matter. A normalized score may require a positive denominator; a metric may require equally sized lists. Reject invalid input clearly instead of returning a plausible-looking result. Type hints explain intent but do not enforce runtime validation by themselves.

Test behavior, not spelling

A meaningful test checks an observable property or known result. For a clipping function, check values below, inside, and above the interval. Include malformed input if your function promises to reject it.

Assertions are convenient for these local exercises. In application code, use explicit exceptions for user-input validation because Python can disable assertions with optimization flags. A test suite should protect the contract while allowing the implementation to change.

PUT THE IDEA INTO CODE

A small experiment you can run.

Clipping avoids exact zero or one when a later computation uses logarithms. Input validation remains separate from clipping.

functions-validation-and-tests.py
def clip_probability(value: float) -> float:
    if not isinstance(value, (int, float)) or not 0 <= value <= 1:
        raise ValueError("Expected a finite number between 0 and 1")
    return min(0.99, max(0.01, float(value)))
assert clip_probability(0) == 0.01
assert clip_probability(0.4) == 0.4
assert clip_probability(1) == 0.99
try:
    clip_probability(float("nan"))
except ValueError:
    print("Invalid input rejected; all checks passed")
Copy code

Save the file, open your terminal in that folder, and run python functions-validation-and-tests.py. Use python3 or py if required by your installation. Setup guide

What to expect

The example rejects NaN and prints that all checks passed.

YOUR TURN

Test an accuracy function.

  1. Require equal-length, nonempty target and prediction lists.
  2. Return the fraction of matching pairs.
  3. Test perfect, completely wrong, and malformed inputs.
Compare with a suggested solution

Raise ValueError before dividing when lists are empty or unequal. For valid inputs, sum(a == b for a, b in zip(actual, predicted)) / len(actual) gives the fraction correct. Check known answers of 1.0, 0.0, and 0.5.

CHECK YOUR UNDERSTANDING

One idea to take with you.

Why reject unequal target and prediction lengths?

Make it part of your progress.

Finish the practice and answer the knowledge check to mark this lesson complete.

Go deeper with primary documentation

Optional references for further study. This lesson and its examples were written for Artificials.

Python language tutorialPython JSON module