# 流量控制¶

“请告诉我，从这里我应该走哪条路？”
“这在很大程度上取决于你想去哪里，”猫说。
“我不在乎在哪里-”爱丽丝说。
“那么你走哪条路都无关紧要，”猫说。
“-只要我能 某处 “爱丽丝补充道，作为一种解释。
“哦，只要你走得够远，”猫说，“你一定会那样做的。”

## 布尔表达式¶

`==`

`!=`

`<`

`<=`

`>`

`>=`

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

```>>> 0.1 + 0.2 == 0.3
False
```

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

A

A

B

A和B

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
```

## 这个 `if` 声明¶

```if <expression>:
<code block>
```

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

```>>> 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')
...
```

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

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

## 这个 `while` 循环¶

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

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

## 这个 `for` 循环¶

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

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

### `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`¶

```>>> 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
```

### `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
```

## 错误¶

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