标签:表达式 print line 使用场景 example 判断 ISE 打折 python技巧
Python assert(断言)用于判断一个表达式,在表达式条件为 false 的时候触发异常。
example1(商店打折):
def apply_discount(product, discount):
price = int(product['price'] * (1.0 - discount))
assert 0 <= price <= product['price']
print(price)
shoes = {'name': 'nike', 'price': 1499}
apply_discount(shoes,0.25)
=> 1124
apply_discount(shoes,2)
=> Traceback (most recent call last):
File "/Users/sangyuming/Desktop/test.py", line 20, in <module>
apply_discount(shoes, 2.5)
File "/Users/sangyuming/Desktop/test.py", line 13, in apply_discount
assert 0 <= price <= product['price']
AssertionError
example2(判断类型):
type_str = 'asdfasdf'
assert type(type_str) == str
=>
assert type(type_str) == int
=>
Traceback (most recent call last):
File "/Users/sangyuming/Desktop/test.py", line 24, in <module>
assert type(type_str) == int
AssertionError
assert [表达式]
等价于:
if not [表达式]:
raise AssertionError
由此可知,[表达式] 实际是if的判断语句
断言不可不用,但也不能乱用
常见错误的用法是把断言当做一个检测错误的的触发条件,把它当做try..except
正确的使用场景如下:
标签:表达式 print line 使用场景 example 判断 ISE 打折 python技巧
原文地址:https://www.cnblogs.com/sangyuming/p/11686797.html