1、Python官方介绍
根据Python官方文档(https://docs.python.org/3/reference/simple_stmts.html#assert)得知Assert statements are a convenient way to insert debugging assertions into a program.
2、用法
[root@wrx crawlent]# python3 Python 3.4.4 (default, Jun 18 2017, 19:00:00) [GCC 4.4.7 20120313 (Red Hat 4.4.7-17)] on linux Type "help", "copyright", "credits" or "license" for more information. >>> assert True,"True:" >>> assert False,"False:" Traceback (most recent call last): File "<stdin>", line 1, in <module> AssertionError: False: >>>
#assert后面跟上表达式,如果表达式为False则返回(异常提示信息)AssertionError:,否则不返回所设置断言提示信息。 #用法一: assert expression 下面的用法和上面等同 if not expression: raise AssertionError() #用法二: assert expression1,espression2 下面的用法和上面等同 if not expression1: raise AssertionError(espression2)
3、举例
[root@wrx crawlent]# python3 Python 3.4.4 (default, Jun 18 2017, 19:00:00) [GCC 4.4.7 20120313 (Red Hat 4.4.7-17)] on linux Type "help", "copyright", "credits" or "license" for more information. >>> s = True >>> assert s >>> assert False Traceback (most recent call last): File "<stdin>", line 1, in <module> AssertionError >>> assert False,"""False""" Traceback (most recent call last): File "<stdin>", line 1, in <module> AssertionError: False >>> assert 3 > 2 ,"3大于2“" >>> assert 3 < 2,"3不小于2" Traceback (most recent call last): File "<stdin>", line 1, in <module> AssertionError: 3不小于2 >>>