Python的断言assert

断言是用来判断是否让程序继续执行的一种辅助策略,可以提前阻止因为有些条件不满足而导致的程序崩溃。

断言的语法非常简单:assert express

如果experss为true, 程序继续执行,如果是false,则返回。

def divide(s):
    n = int(s)
    assert n != 0, 's should not be zero.'
    print('Going to divide 100 by {}'.format(s))
    return 100 / n


divide(0)

 程序的输出为:

Traceback (most recent call last):
  File "/Users/xxx/PycharmProjects/netbarclient/httpproxy.py", line 8, in <module>
    divide(0)
  File "/Users/xxx/PycharmProjects/netbarclient/httpproxy.py", line 3, in divide
    assert n != 0, 's should not be zero.'
AssertionError: s should not be zero.

Process finished with exit code 1

 

如果在正式环境中关闭断言,方法是添加 -O 参数

python -O haproxy.py

转载于:https://www.cnblogs.com/diaolanshan/p/8810633.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值