Python assert 断言

Python assert 断言

使用语法为:

assert expression [, arguments]

当expression为False时,触发异常,并返回arguments。在这里的arguments可以为字符串或者其他表达式等。


例1(无参数):

def test(a):
    assert len(a)<10, 

a = [x for x in range(20)]
test(a)

例1错误信息为:

Traceback (most recent call last):
  File "/Users/lixiang/Desktop/ForJob/Py_assert.py", line 5, in <module>
    test(a)
  File "/Users/lixiang/Desktop/ForJob/Py_assert.py", line 2, in test
    assert len(a)<10
AssertionError

例2(参数为字符串):

def test(a):
    assert len(a)<10, 'Input is too long'

a = [x for x in range(20)]
test(a)

例2错误信息为:

Traceback (most recent call last):
  File "/Users/lixiang/Desktop/ForJob/Py_assert.py", line 7, in <module>
    test(a)
  File "/Users/lixiang/Desktop/ForJob/Py_assert.py", line 4, in test
    assert len(a)<10, 'Input is too long'
AssertionError: Input is too long

例3(参数为表达式):
个人想法:可以利用表达式这个特性,来动态地根据错误发生的实际情况来产生不同的错误信息,以便更好地来查找错误。

def test(a):
    assert len(a)<10, 'The length of input is ' + str(len(a)) + ' , and we just need 10.'

a = [x for x in range(20)]
test(a)

例3错误信息为:

Traceback (most recent call last):
  File "/Users/lixiang/Desktop/ForJob/Py_assert.py", line 7, in <module>
    test(a)
  File "/Users/lixiang/Desktop/ForJob/Py_assert.py", line 4, in test
    assert len(a)<10, 'The length of input is ' + str(len(a)) + ' , and we just need 10.'
AssertionError: The length of input is 20 , and we just need 10.

assert 和 if not … raise 实现相同功能:
例4:

def test(a):
    if not len(a)<10:
        raise ValueError

a = [x for x in range(20)]
test(a)

例4错误信息:

Traceback (most recent call last):
  File "/Users/lixiang/Desktop/ForJob/Py_assert.py", line 8, in <module>
    test(a)
  File "/Users/lixiang/Desktop/ForJob/Py_assert.py", line 5, in test
    raise ValueError
ValueError
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值