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
  • 相关阅读:
    Windows10远程桌面连接提示:出现身份验证错误,要求的函数不受支持
    mybatis 中 if-test 判断大坑
    hutool的DateUtil工具类
    SpringBoot启动过程
    数据库事务的隔离级别
    EasyUI管理后台模板(附源码)
    springmvc中自定义拦截器以及拦截器的执行过程
    文件上传(MultipartFile)
    文件下载(使用springmvc框架中ResponseEntity对象)
    json格式实现数据传输
  • 原文地址:https://www.cnblogs.com/xuechaojun/p/10200770.html
Copyright © 2011-2022 走看看