Python基础教程

005_assert条件与异常

assert条件与异常

assert条件与异常

assert(断言)语句就是一个条件判断,如果判断为真则什么都不发生,如果判断为假则发生AssertionError异常。

示例代码如下

print("hello")
a = 0
assert a == 0, '不发生assert异常,a=0'
assert a > 0, '发生了assert异常,a>0'
print("world")

运行结果

C:UsershccmaAnaconda3python.exe E:/wkp01/p00/test01/atestpkg/t33.py
Traceback (most recent call last):
  File "E:/wkp01/p00/test01/atestpkg/t33.py", line 4, in <module>
    assert a > 0, '发生了assert异常,a>0'
AssertionError: 发生了assert异常,a>0
hello

Process finished with exit code 1

assert与try...except配合使用

assert与try...except配合使用示例如下。

import traceback

# 定义除法函数
def divi(x,y):
    try:
        assert x>y,"输入的数据要求x>y"
        z=x/y
        return z
    except Exception as e:
        print("发生了assert异常")
        print(e)
        print(traceback.format_exc())

res=divi(6,2)
print(res)
res=divi(2,6)
print(res)

运行结果如下

C:UsershccmaAnaconda3python.exe E:/wkp01/p00/test01/atestpkg/t32.py
3.0
发生了assert异常
输入的数据要求x>y
Traceback (most recent call last):
  File "E:/wkp01/p00/test01/atestpkg/t32.py", line 6, in divi
    assert x>y,"输入的数据要求x>y"
AssertionError: 输入的数据要求x>y

None

Process finished with exit code 0
这篇文章对您有用吗?

我们要如何帮助您?