Python’s assert statement

Python’s assert statement asserts that a value is True. If the value is not True, an AssertionError is raised.

Consider the following code.

assert True
assert False

The first line basically does nothing because the argument to assert is True. The second line will throw an AssertionError.

The assert statement is useful for explaining code. Let’s say I wrote a piece of code to explain how to add numbers in Python.

sum = 2 + 2
assert sum == 4

The assert line asserts that the variable sum must equal 4 – otherwise the code wouldn’t work. Without assert, the above code would have to be written like this.

sum = 2 + 2
# sum now equals 4

Having the assert statement makes it a little more eloquent to write about code.

Leave a Reply

Your email address will not be published. Required fields are marked *