Skip to main content

流程控制

布尔

虽然整型、浮点型和字符串数据类型有无数种可能的值,但“布尔”(Boolean)数据类型只有两种值: TrueFalse

大多数 Python 对象都能用作布尔类型

  • 数字 00.00+0j 都是 False,其他数字均为 True
  • 空串 ""False,其他字符串均为 True
  • 空列表 []False,其他列表均为 True
  • 空字典 {}False,其他字典均为 True
  • 空集合 ()False,其他集合均为 True
  • Python 的特殊值 None 始终为 False

二元布尔操作符

and 操作符的真值表

表达式求值为
True and TrueTrue
True and FalseFalse
False and TrueFalse
False and FalseFalse

or 操作符的真值表

表达式求值为
True or TrueTrue
True or FalseTrue
False or TrueTrue
False or FalseFalse

not 操作符的真值表

表达式求值为
not TrueFalse
not FalseTrue

三元运算符

python中没有三元运算符,只能通过以下方式替代
var = a - b if a > b else a + b

while 循环

完整的 while 循环结构如下:

while condition:
body
else:
post-code
info

while 循环的 else 部分是可选的,且不常用到,一般简写如下:

while condition:
body
post-code
tip

while 循环的 body 部分,可以使用 breakcontinue 来终止循环或者跳过循环。

if-elif-else 语句

完整结构如下:

if condition1:
body1
elif condition2:
body2
elif condition3:
body3
else:
body4
Python 中没有 case 语句

通常情况下,可使用 if...elif...elif...else 来应对,如果遇到特殊情况,可使用函数字典来解决:

def do_a_stuff():
# process a
def do_b_stuff():
# process b
def do_c_stuff():
# process c
func_dict = {'a': do_a_stuff,
'b': do_b_stuff,
'c': do_c_stuff}
x = 'a'
func_dict[x]()

for 循环

for item in sequence:
body
else:
post-code
info

else 部分是可选的。像 while 循环的 else 部分一样,很少被用到。breakcontinuefor 循环中的作用,和在 while 循环中是一样的。

range 函数

对于给出的数字 nrange(n) 会返回 012……n-2n-1

有时候循环中需要显式的索引(如值在列表中出现的位置)。这时可以将 range 函数和 len 函数结合起来使用,生成供 for 循环使用的索引序列。

x = [1, 3, -7, 4, 9, -5, 4]
for i in range(len(x)):
if x[i] < 0:
print("Found a negative number at index ", i)

元组拆包

somelist = [(1, 2), (3, 7), (9, 5)]
result = 0
for x, y in somelist:
result = result + (x * y)

enumerate 函数

enumerate 函数返回的是元组(索引,数据项)。

通过组合使用元组拆包和 enumerate 函数,可以实现同时对数据项及其索引进行循环遍历。用法与 range 函数类似,优点是代码更清晰、更易理解。

x = [1, 3, -7, 4, 9, -5, 4]
for i, n in enumerate(x):
if n < 0:
print("Found a negative number at index ", i)

列表推导式

new_list = [expression1 for variable in old_list if expression2]

>>> x = [1, 2, 3, 4]
>>> x_squared = [item * item for item in x]
>>> x_squared
[1, 4, 9, 16]
>>> x = [1, 2, 3, 4]
>>> x_squared = [item * item for item in x if item > 2]
>>> x_squared
[9, 16]

字典推导式

new_dict = {expression1:expression2 for variable in list if expression3}

>>> x = [1, 2, 3, 4]
>>> x_squared_dict = {item: item * item for item in x}
>>> x_squared_dict
{1: 1, 2: 4, 3: 9, 4: 16}