python assert断言的实例用法
作者:小妮浅浅 时间:2023-06-24 22:15:42
断言声明是一种方便的程序调试方式。
1、可将断言视为debug工具,Python的实现也符合这种设计理念。assert语句的执行依赖于__debug__,且默认值为True。
2、如果__debug__为True,则仅执行assert语句。
实例
assert 可以同时声明两个 expression,例如 assert expression1, expression2 等价于
if __debug__:
if not expression1: raise AssertionError(expression2)
如果执行脚本文件时加上-O参数, __debug__则为False。
知识点扩展:
简单用法是:
assert expression
让我们用程序来测试这个expression,如果expression相当于False,那么raise一个AssertionError出来。
即逻辑上等同于:
if not expression:
raise AssertionError
简单看看这些例子:
>>> assert True
>>> assert False
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
assert False
AssertionError
>>> assert 1==1
>>> assert 1==0
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
assert 1==0
AssertionError
>>> assert [1, 2] # 非空列表值得注意一下,虽说也没个啥,哈哈
>>> assert not [1, 2]
Traceback (most recent call last):
File "<ipython-input-48-eae410664122>", line 1, in <module>
assert not [1, 2]
AssertionError
来源:https://www.py.cn/jishu/jichu/33869.html
标签:python,assert
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
23个MySQL数据库安全使用技巧
2007-10-26 16:02:00
NumPy索引与切片的用法示例总结
2022-05-13 19:33:38
![](https://img.aspxhome.com/file/2023/4/80544_0s.png)
js星级评分代码
2008-05-02 21:07:00
![](https://img.aspxhome.com/file/UploadPic/20085/2/star_78s.gif)
python argparse 模块命令行参数用法及说明
2023-10-26 00:08:27
![](https://img.aspxhome.com/file/2023/7/102997_0s.png)
关于windows下Tensorflow和pytorch安装教程
2023-06-09 07:35:54
![](https://img.aspxhome.com/file/2023/5/70695_0s.png)
django基础学习之send_mail功能
2023-04-01 00:16:53
详解python读写json文件
2022-11-01 16:18:53
解决python web项目意外关闭,但占用端口的问题
2023-02-11 19:18:53
Access函数大全
2009-12-23 19:22:00
SqlServer 索引自动优化工具
2012-10-07 10:41:09
caffe binaryproto 与 npy相互转换的实例讲解
2021-10-22 15:38:48
PyTorch两种安装方法
2022-04-16 04:11:50
![](https://img.aspxhome.com/file/2023/6/76166_0s.png)
SQL进行排序、分组、统计的10个新技巧
2009-01-23 13:59:00
对python3 sort sorted 函数的应用详解
2022-08-01 23:44:45
JQuery判断radio(单选框)是否选中和获取选中值方法总结
2024-04-19 10:24:11
JavaScript使用ZeroClipboard操作剪切板
2024-04-29 13:38:14
python实现微信小程序的多种支付方式
2021-03-26 21:38:58
![](https://img.aspxhome.com/file/2023/7/127147_0s.png)
ASp使用AspJpeg组件制作透明文字水印
2008-01-15 20:25:00
![](https://img.aspxhome.com/file/UploadPic/20081/15/2008115202930732s.jpg)
python创建线程示例
2021-07-21 00:20:37
JavaScript 日期联动选择器
2010-08-01 10:18:00