assert "条件判断", "条件不满足时输出的提示信息"
def div(x, y):
assert isinstance(x, (float, int)) and isinstance(y, (float, int)), \
"param `x` and `y` expected to be 'int' or 'float' type"
assert y != 0, "param `y` should not to be exactly `0`"
return x/y
div(1, "2")
---------------------------------------------------------------------------
AssertionError Traceback (most recent call last)
<ipython-input-206-579e0bede4d8> in <module>
----> 1 div(1, "2")
<ipython-input-205-258ec937e818> in div(x, y)
1 def div(x, y):
2 assert isinstance(x, (float, int)) and isinstance(y, (float, int)), \
----> 3 "param `x` and `y` expected to be 'int' or 'float' type"
4 assert y != 0, "param `y` should not to be exactly `0`"
5 return x/y
AssertionError: param `x` and `y` expected to be 'int' or 'float' type
raise 异常类名称(描述信息)
def div(x, y):
if not isinstance(x, (float, int)) or not isinstance(y, (float, int)):
raise TypeError("param `x` and `y` expected to be 'int' or 'float' type")
if y == 0:
raise ZeroDivisionError("param `y` should not to be exactly `0`")
return x/y
div(1, 0)
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
<ipython-input-213-4267cdef819f> in <module>
----> 1 div(1, 0)
<ipython-input-212-dce337c4d91a> in div(x, y)
3 raise TypeError("param `x` and `y` expected to be 'int' or 'float' type")
4 if y == 0:
----> 5 raise ZeroDivisionError("param `y` should not to be exactly `0`")
6 return x/y
ZeroDivisionError: param `y` should not to be exactly `0`
由于除数为0,raise关键字触发异常
福 利
CSDN旗下公众号全新搜索技能上线啦!
只要在公众号内回复消息
就能自动回复想搜索的内容啦!
现在体验有惊喜,每日参与搜索打卡,
连续打卡满3天、7天、14天
均有CSDN精美礼品相送 百分百有礼!快戳
![]()
更多精彩推荐
☞倪光南、求伯君“出山”:爱解 Bug、无惧“35岁魔咒”、编码之路痛并快乐!
☞饿了么技术往事![]()
点分享 ![]()
点点赞 ![]()
点在看