Python assert 关键字
每种编程语言都有处理程序执行过程中引发的异常的功能。在 Python 中,assert 关键字用于捕获错误并提示用户自定义错误消息,而不是系统生成的错误消息。当发生错误时,这可以帮助程序员轻松找到并修复错误。
带有 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
如果没有 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
广告