python学习之assert语句


assert语句用于代码检测并报警。

语法

assert code...

例子

# -*- coding: utf-8 -*-
# assert语句说明
a,b= 1,23

a == 2
assert b >=21
assert b <=22

 结果

Traceback (most recent call last): File "C:\Users\huangrong\Desktop\test.py", line 7, in <module> assert b <=22 AssertionError [Finished in 0.1s]

分析

"a == 2"错了,但并没有报错,因为没有使用assert。

"b <=22"报错了!因为使用了assert。

 常用的处理错误方式

# -*- coding: utf-8 -*-
# assert语句说明

a,b= 1,23

try:
	assert a == 2
except Exception as e:
	print('hello')

说明: Exception表示捕获所有异常。

执行结果

hello [Finished in 0.1s]

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM