Search code examples
pythonassert

How do you assert something is not true in Python?


In trying to understand assert in Python, specifically inverting it, I came up with this...

>>> assert != ( 5 > 2 )
>>> assert != ( 2 > 5 )

Now the first line fails and the second passes. What's the idiomatic way to assert something is false?


Solution

  • You'd use the boolean not operator, not the != inequality comparison operator:

    >>> assert not (5 > 2)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    AssertionError
    >>> assert not (2 > 5)
    

    An assert passes if the test is true in the boolean sense, so you need to use the boolean not operator to invert the test.