assert statement asserts that a value is
True. If the value is not
AssertionError is raised.
Consider the following code.
assert True assert False
The first line basically does nothing because the argument to
True. The second line will throw an
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
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
assert statement makes it a little more eloquent to write about code.