三元运算符 & assert 断言

1、三元运算符

Python 中的三元运算符语法如下:

x = a if 条件 else b

例如:

L1 = ['Hello','World',18,'Apple']

L2 = [x.lower() for x in L1 if isinstance(x,str)]

>> ['hello', 'world', 'apple']

L2 = [x.lower() if isinstance(x,str) else x for x in L1]

>> ['hello', 'world', 18, 'apple', None]

2、Assert 断言

assert 这个关键字称为断言。当这个关键字后面的条件为假时,程序自动崩溃并抛出AssertionError异常。比如:assert 4>3 可以正常运行,assert 3>4就会抛出异常。例如在程序中输入如下代码,则会抛出异常:

x1 = 3
x2 = 4
assert x1>x2

报错信息如下:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError

一般来说,我们可以用它在程序中植入检查点,放置在需要确保条件为真程序才能正常运行的地方。

Guess you like

Origin blog.csdn.net/Zhaopanp_Crise/article/details/102762163