流量控制

“请告诉我,我从这里该走哪条路?”
“这很大程度上取决于你想去哪里,”猫说。
“我不太在乎在哪里——”爱丽丝说。
“那你走哪条路也没关系,”猫说。
“——只要我得到 在某处 ”爱丽丝补充道。
“哦,你一定要这么做,”猫说,“如果你走得够长的话。”

Alice's Adventures in Wonderland

到现在为止,密码战更像是…令人印象深刻。每次只执行一系列命令。但是随着程序控制流的引入,一个全新的程序世界展现了它自己。使用控制流工具以处理复杂任务的方式构造代码取决于您的经验和创造力。

布尔表达式

了解布尔表达式对于程序的控制流是必不可少的。python非常直观地处理这个问题。最重要的布尔运算是

==

等于

!=

不等于

<

小于

<=

小于或等于

>

大于

>=

大于或等于

>>> 1 == 1
True
>>> 1 + 1 != 2
False
>>> 5*2 >= 11
False

警告

当心 float 比较,因为计算机在内部表示浮点数字的方式可能会导致一些看似奇怪的行为。

>>> 0.1 + 0.2 == 0.3
False

这当然是意想不到的行为。为了解决这个缺点,3.5版的python引入了 isclose 在其功能 math 模块。

>>> import math
>>> math.isclose(0.1 + 0.2, 0.3)  
True

如果您使用的是旧版本,仍然有一些方便的解决方案。这个 numpy 本教程后面介绍的包还提供了 float 比较。

在许多情况下,简单的布尔表达式不足以正确地指定程序的控制流。有时,代码块只能在不满足某个条件、同时满足多个条件或至少满足其中一个条件时执行。因为这个 Python 有关键词 notandor ,分别。下表概述了它们的行为。

的真值表 not

A

不是一个

的真值表 and

A

B

A和B

的真值表 or

A

B

A或B

使用这些关键字组合布尔表达式是编程的基本技能。

>>> i = 3
>>> i < 4 and i >= 0
True
>>> i < 4 and i > 3
False
>>> i < 4 and not i > 3
True
>>> i >= 0 or i > 3
True

您还可以像在公式中那样使用括号来指定子表达式的计算顺序。

注解

在 Python 中 False 并不是Python中唯一“假”的东西。 FalseNone ,所有类型的数字零,以及空字符串和容器都被解释为假。

下面介绍使用布尔表达式的最重要的构造。

这个 if 陈述

每种编程语言提供的一个构造是 if statement .基本结构如下:

if <expression>:
    <code block>

结果是 代码块 仅在以下情况下执行 表达True .

注解

试验

>>> x = 0
>>> y = 1
>>> if x > 0:
...     print('Larger than 0')
...
>>> if y > 0:
...     print('Larger than 0')
...
Larger than 0

这个 表达 也可以包括否定使用 Boolean operations

>>> x = 0
>>> y = 1
>>> if not x > 0:
...     print('Not larger than 0')
...
Not larger than 0
>>> if not y > 0:
...     print('Not larger than 0')
...

如果您想涵盖这两种情况,也可以使用 else 关键字:

>>> x = 1
>>> if x < 0:
...     print('Negative')
... else:
...     print('Positive')
...
Positive

但正如你所看到的,这并不涵盖所有的案件。如果…怎么办 x 是0?为此我们必须使用 elif

>>> x = 0
>>> if x < 0:
...     print('Negative')
... elif x == 0:
...     print('Zero')
... else:
...     print('Positive')
...
Zero

你可以加上 elifs 随你的便。

这个 while

有时需要执行一个例行程序,直到满足某个条件。这是通过使用 while loop .

>>> x = 0
>>> while x < 5:
...     print(x)
...     x += 1
...
0
1
2
3
4

假设您想退出 while loop 当满足一定条件时。这是可能的 the break statement .

>>> x = 0
>>> while x < 5:
...     if x == 3:
...         break
...     print(x)
...     x += 1
...
0
1
2

注意

虽然 while loops 在每种编程语言中都是一块常见的基石,我建议您尽可能避免使用它们。很容易,退出循环的标准从未达到,并且程序执行相同任务的频率比预期的要高。在许多情况下 while loop 可替换为 for loop .

这个 for

在很多情况下,您只想一次处理一个容器的所有元素。这很容易实现 for loops .

>>> x = [1, 2, 3]
>>> for i in x:
...     print(i)
...
1
2
3

在这里 i 接受元素的值 x 一个接一个。这使你可以与 i 在这个里面 for loop .访问完所有元素后,您将自动退出循环。一个更复杂的例子可能是将另一个列表的平方值存储在一个新列表中。

>>> x = [1, 2, 3]
>>> x_squared = []
>>> for value in x:
...     x_squared.append(value**2)
...
>>> print(x_squared)
[1, 4, 9]

range

循环整数的快捷方式是 range() 功能。

>>> for i in range(3):
...     print(i)
...
0
1
2
>>> for i in range(3, 6):
...     print(i)
...
3
4
5
>>> for i in range(3, 12, 3):
...     print(i)
...
3
6
9

enumerate

有时,您还希望跟踪您当前在迭代中的位置。例如,您想知道程序的当前状态是什么,但是在每个时间打印正在操作的值有点太多了。然后你可以用 enumerate() 这样地:

>>> results = []
>>> for i, value in enumerate(range(100,900)):
...     if i % 200 == 0:
...         print('Current step:', i, '-- Value:', value)
...     results.append(i**2 % 19)
...
Current step: 0 -- Value: 100
Current step: 200 -- Value: 300
Current step: 400 -- Value: 500
Current step: 600 -- Value: 700

如您所见,我们现在有逗号分隔的变量 ivalue . i 获取当前的索引,而 value 保存容器的实际对象。

zip

另一个常见的任务是您必须同时循环几个列表。使用 :func:``zip` `功能:

>>> fruits = ['banana', 'orange', 'cherry']
>>> colors = ['yellow', 'orange', 'red']
>>> for fruit, color in zip(fruits, colors):
...     print('The color of', fruit, 'is', color)
...
The color of banana is yellow
The color of orange is orange
The color of cherry is red

注解

zip() 停止 for 循环一次 list 是空的:

>>> fruits = ['banana', 'orange', 'cherry', 'apple', 'lemon']
>>> colors = ['yellow', 'orange', 'red']
>>> for fruit, color in zip(fruits, colors):
...     print('The color of', fruit, 'is', color)
...
The color of banana is yellow
The color of orange is orange
The color of cherry is red

错误

因为python是一种动态语言,所以永远不能保证函数的输入是您想要的。以一个函数为例,该函数的目的是计算一个数的位数之和。如果偶然有人将字符串作为参数传递给这个函数呢?因此,在某些情况下,最好检查函数的输入是否正常。如果输入不支持此测试,您可以 raise 错误如下:

>>> raise ValueError('The input was wrong')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: The input was wrong

总结