As an example of the use of assert
, suppose you have a function that calculates the vector (cross) product of two vectors represented as list
objects. This product is only defined for three-dimensional vectors, so calling it with lists of any other length is an error:
>>> def cross_product(a, b):
... assert len(a) == len(b) == 3, 'Vectors a, b must be three-dimensional'
... return [a[1]*b[2] - a[2]*b[1],
... a[2]*b[0] - a[0]*b[2],
... a[0]*b[1] - a[1]*b[0]]
...
>>> cross_product([1, 2, -1], [2, 0, -1, 3]) # Oops
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in cross_product
AssertionError: Vectors a, b must be three-dimensional
>>> cross_product([1, 2, -1], [2, 0, -1])
[-2, -1, -4]