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热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短