你如何断言某些东西在Python中是不正确的?

时间:2014-06-26 20:11:15

标签: python assert

在尝试理解Python中的assert时,特别是反转它,我想出了这个......

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

现在第一行失败,第二行失败。断言某事的惯用方法是假的?

1 个答案:

答案 0 :(得分:13)

您使用的是boolean not operator,而不是!=不等式比较运算符:

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

如果测试在布尔意义上为真,则assert通过,因此您需要使用布尔not运算符来反转测试。