zoukankan      html  css  js  c++  java
  • Python全栈开发之---assert断言

    一、python assert的作用:

    根据Python 官方文档解释(https://docs.python.org/3/reference/simple_stmts.html#assert), "Assert statements are a convenient way to insert debugging assertions into a program".

    二、一般的用法是:

    1 assert condition
    2 用来让程序测试这个condition,如果condition为false,那么raise一个AssertionError出来。逻辑上等同于:
    3 
    4 if not condition:
    5     raise AssertionError()

    例如:

     1 >>> assert 1==1
     2 >>> assert 1==0
     3 Traceback (most recent call last):
     4   File "<pyshell#1>", line 1, in <module>
     5     assert 1==0
     6 AssertionError
     7 >>> assert True
     8 >>> assert False
     9 Traceback (most recent call last):
    10   File "<pyshell#3>", line 1, in <module>
    11     assert False
    12 AssertionError
    13 >>> assert 3<2
    14 Traceback (most recent call last):
    15   File "<pyshell#4>", line 1, in <module>
    16     assert 3<2
    17 AssertionError

    三、如何为assert断言语句添加异常参数

      assert的异常参数,其实就是在断言表达式后添加字符串信息,用来解释断言并更好的知道是哪里出了问题。格式如下:

    assert expression [, arguments]
    assert 表达式 [, 参数]

    例如:

     1 >>> assert len(lists) >=5,'列表元素个数小于5'
     2 Traceback (most recent call last):
     3 File "D:/Data/Python/helloworld/helloworld.py", line 1, in <module>
     4 assert 2>=5,'列表元素个数小于5'
     5 AssertionError: 列表元素个数小于5
     6 >>> assert 2==1,'2不等于1'
     7 Traceback (most recent call last):
     8 File "D:/Data/Python/helloworld/helloworld.py", line 1, in <module>
     9 assert 2==1,'2不等于1'
    10 AssertionError: 2不等于1
  • 相关阅读:
    桥接,NAT,Host Only的区别
    PHP并发IO编程之路
    Git SSH Key 生成步骤
    composer安装学习
    db file sequential read等待事件的一点研究
    多个hints 怎么写?
    再次遭遇笛卡尔积
    pl/sql 在一个程序块里打印日志输出到表格
    pl/sql 程序块里打印问题
    利用ordered hints优化SQL
  • 原文地址:https://www.cnblogs.com/xuechaojun/p/10200770.html
Copyright © 2011-2022 走看看