# 1.5 控制

## 1.5.1 语句

``````>>> def square(x):
mul(x, x) # Watch out! This call doesn't return a value.
``````

``````>>> def square(x):
return mul(x, x)
``````

``````>>> def print_square(x):
print(square(x))
``````

## 1.5.2 复合语句

``````<header>:
<statement>
<statement>
...
<statement>
<statement>
...
...
``````

• 表达式、返回语句和赋值语句都是简单语句。
• `def`语句是复合语句。`def`头部之后的组定义了函数体。

• 执行语句序列需要执行第一条语句。如果这个语句不是重定向控制，之后执行语句序列的剩余部分，如果存在的话。

## 1.5.3 定义函数 II：局部赋值

``````>>> def percent_difference(x, y):
difference = abs(x-y)
return 100 * difference / x
>>> percent_difference(40, 50)
25.0
``````

``````>>> def percent_difference(x, y):
return 100 * abs(x-y) / x
``````

## 1.5.4 条件语句

Python 拥有内建的绝对值函数：

``````>>> abs(-2)
2
``````

``````>>> def absolute_value(x):
"""Compute abs(x)."""
if x > 0:
return x
elif x == 0:
return 0
else:
return -x

>>> absolute_value(-2) == abs(-2)
True
``````

`absolute_value`的实现展示了一些重要的事情：

``````if <expression>:
<suite>
elif <expression>:
<suite>
else:
<suite>
``````

1. 求出头部中的表达式。
2. 如果它为真，执行语句组。之后，跳过条件语句中随后的所有子句。

``````>>> 4 < 2
False
>>> 5 >= 5
True
``````

``````>>> 0 == -0
True
``````

``````>>> True and False
False
>>> True or False
True
>>> not False
True
``````

1. 求出子表达式`<left>`
2. 如果结果`v`是假值，那么表达式求值为`v`
3. 否则表达式的值为子表达式`<right>`

1. 求出子表达式`<left>`
2. 如果结果`v`是真值，那么表达式求值为`v`
3. 否则表达式的值为子表达式`<right>`

1. 求出`<exp>`，如果值是`True`那么返回值是假值，如果为`False`则反之。

## 1.5.5 迭代

``````0, 1, 1, 2, 3, 5, 8, 13, 21, ...
``````

``````>>> def fib(n):
"""Compute the nth Fibonacci number, for n >= 2."""
pred, curr = 0, 1   # Fibonacci numbers
k = 2               # Position of curr in the sequence
while k < n:
pred, curr = curr, pred + curr  # Re-bind pred and curr
k = k + 1                       # Re-bind k
return curr
>>> fib(8)
13
``````

``````pred, curr = curr, pred + curr
``````

`while`子句包含一个头部表达式，之后是语句组：

``````while <expression>:
<suite>
``````

1. 求出头部表达式。
2. 如果它为真，执行语句组，之后返回到步骤 1。

## 1.5.6 实践指南：测试

``````>>> assert fib(8) == 13, 'The 8th Fibonacci number should be 13'
``````

`fib`编写的`test`函数测试了几个参数，包含`n`的极限值：

``````>>> def fib_test():
assert fib(2) == 1, 'The 2nd Fibonacci number should be 1'
assert fib(3) == 1, 'The 3nd Fibonacci number should be 1'
assert fib(50) == 7778742049, 'Error at the 50th Fibonacci number'
``````

Doctest。Python 提供了一个便利的方法，将简单的测试直接写到函数的文档字符串内。文档字符串的第一行应该包含单行的函数描述，后面是一个空行。参数和行为的详细描述可以跟随在后面。此外，文档字符串可以包含调用该函数的简单交互式会话：

``````>>> def sum_naturals(n):
"""Return the sum of the first n natural numbers

>>> sum_naturals(10)
55
>>> sum_naturals(100)
5050
"""
total, k = 0, 1
while k <= n:
total, k = total + k, k + 1
``````

``````>>> from doctest import run_docstring_examples
>>> run_docstring_examples(sum_naturals, globals())
``````

``````python3 -m doctest <python_source_file>
``````