Python中的assert关键字

每种编程语言都具有处理程序执行过程中引发的异常的功能。在python中,关键字assert用于捕获错误并提示用户定义的错误消息,而不是系统生成的错误消息。这使程序员很容易在错误发生时定位并修复错误。

有断言

在下面的示例中,我们使用assert关键字捕获零误差除法。该消息是按照程序员的意愿编写的。

示例

x = 4
y = 0
assert y != 0, "if you divide by 0 it gives error"
print("Given values are ","x:",x ,"y:",y)
print("\nmultiplication of x and y is",x * y)
print("\ndivision of x and y is",x / y)

运行上面的代码将为我们提供以下结果:

Traceback (most recent call last):
File "scratch.py", line 3, in
assert y != 0, "if you divide by 0 it gives error"
AssertionError: if you divide by 0 it gives error

没有断言

如果没有assert语句,我们将得到系统生成的错误,可能需要进一步调查以了解并找到错误的来源。

示例

x = 4
y = 0
#assert y != 0, "if you divide by 0 it gives error"
print("Given values are ","x:",x ,"y:",y)
print("\nmultiplication of x and y is",x * y)
print("\ndivision of x and y is",x / y)

运行上面的代码将为我们提供以下结果:

multiplication of x and y is 0
Traceback (most recent call last):
File "scratch.py", line 6, in <module>
print("\ndivision of x and y is",x / y)
ZeroDivisionError: division by zero