# Python 教程 6 — 有返回值的函数

## 1.返回值 #

```e = math.exp(1.0)

```def area(radius):
return a```

```def area(radius):

```def absolute_value(x):
if x < 0:
return -x
else:
return x```

```def absolute_value(x):
if x < 0:
return -x
if x > 0:
return x```

```>>> absolute_value(0)
None```

## 2.增量式开发 #

```def distance(x1, y1, x2, y2):
return 0.0```

```>>> distance(1, 2, 4, 6)
0.0```

```def distance(x1, y1, x2, y2):
dx = x2 - x1
dy = y2 - y1
print('dx is', dx)
print('dy is', dy)
return 0.0```

```def distance(x1, y1, x2, y2):
dx = x2 - x1
dy = y2 - y1
dsquared = dx**2 + dy**2
print('dsquared is: ', dsquared)
return 0.0```

```def distance(x1, y1, x2, y2):
dx = x2 - x1
dy = y2 - y1
dsquared = dx**2 + dy**2
result = math.sqrt(dsquared)
return result```

1. 从一个能运行的程序开始，并且每次只增加少量改动。无论你何时遇到错误，都能够清楚定位错误的源头。
2. 用临时变量存储中间值，这样你就能显示并检查它们。
3. 一旦程序正确运行，你要删除一些脚手架代码，或者将多条语句组成复合表达式，但是前提是不会影响程序的可读性。

## 3.组合 #

```radius = distance(xc, yc, xp, yp)
```

```result = area(radius)
```

```def circle_area(xc, yc, xp, yp):
radius = distance(xc, yc, xp, yp)
return result```

```def circle_area(xc, yc, xp, yp):
return area(distance(xc, yc, xp, yp))```

## 4.布尔函数 #

```def is_divisible(x, y):
if x % y == 0:
return True
else:
return False```

```>>> is_divisible(6, 4)
False
>>> is_divisible(6, 3)
True```

`==`运算符的结果是布尔值，因此我们直接返回它，让代码变得更简洁。

```def is_divisible(x, y):
return x % y == 0```

```if is_divisible(x, y):
print('x is divisible by y')```

```if is_divisible(x, y) == True:
print('x is divisible by y')```

## 5.再谈递归 #

`def factorial(n):`

```def factorial(n):
if n == 0:
return 1```

```def factorial(n):
if n == 0:
return 1
else:
recurse = factorial(n-1)
result = n * recurse
return result```

## 7.再举一例 #

F(0)=0，F(1)=1, F(n)=F(n – 1)+F(n – 2)（≥ 2，∈ N*）

```def fibonacci (n):
if n == 0:
return 0
elif  n == 1:
return 1
else:
return fibonacci(n-1) + fibonacci(n-2)```

## 8.检查类型 #

```>>> factorial(1.5)
RuntimeError: Maximum recursion depth exceeded```

```def factorial (n):
if not isinstance(n, int):
print('Factorial is only defined for integers.')
return None
elif n < 0:
print('Factorial is not defined for negative integers.')
return None
elif n == 0:
return 1
else:
return n * factorial(n-1)```

```>>> factorial('fred')
Factorial is only defined for integers.
None
>>> factorial(-2)
Factorial is not defined for negative integers.
None```

## 9.调试 #

• 该函数获得的实参有些问题，违反先决条件。
• 该函数有些问题，违反后置条件。
• 返回值或者它的使用方法有问题。

```def factorial(n):
space = ' ' * (4 * n)
print(space, 'factorial', n)
if n == 0:
print(space, 'returning 1')
return 1
else:
recurse = factorial(n-1)
result = n * recurse
print(space, 'returning', result)
return result```

`space`是一个空格字符的字符串，用来控制输出的缩进。 下面是 `factorial(4)` 的输出结果：

```                factorial 4
factorial 3
factorial 2
factorial 1
factorial 0
returning 1
returning 1
returning 2
returning 6
returning 24```

## 11.练习题 #

### 习题6-1 #

```def b(z):
prod = a(z, z)
print(z, prod)
return prod

def a(x, y):
x = x + 1
return x * y

def c(x, y, z):
total = x + y + z
square = b(total)**2
return square

x = 1
y = x + 1
print(c(x, y+3, x+y))```

### 习题6-2 #

Ackermann函数定义如下：

```"""This module contains a code example related to
Think Python, 2nd Edition
by Allen Downey
http://thinkpython2.com
"""

from __future__ import print_function, division

def ackermann(m, n):
"""Computes the Ackermann function A(m, n)
See http://en.wikipedia.org/wiki/Ackermann_function
n, m: non-negative integers
"""
if m == 0:
return n+1
if n == 0:
return ackermann(m-1, 1)
return ackermann(m-1, ackermann(m, n-1))

print(ackermann(3, 4))```

### 习题6-3 #

```def first(word):
return word[0]

def last(word):
return word[-1]

def middle(word):
return word[1:-1]```

1. 将它们录入到文件 `palindrome.py` 中并测试。当你用一个两个字母的字符串调用 `middle` 时会发生什么？一个字母的呢？空字符串呢？空字符串这样 `''` 表示，中间不含任何字母。
2. 编写一个叫 `is_palindrome` 的函数，接受一个字符串作为实参。如果是回文词，就返回 `True` ，反之则返回 `False`。记住，你可以使用内建函数 `len` 来检查字符串的长度。
```"""This module contains a code example related to
Think Python, 2nd Edition
by Allen Downey
http://thinkpython2.com
"""

from __future__ import print_function, division

def first(word):
"""Returns the first character of a string."""
return word[0]

def last(word):
"""Returns the last of a string."""
return word[-1]

def middle(word):
"""Returns all but the first and last characters of a string."""
return word[1:-1]

def is_palindrome(word):
"""Returns True if word is a palindrome."""
if len(word) <= 1:
return True
if first(word) != last(word):
return False
return is_palindrome(middle(word))

print(is_palindrome('allen'))
print(is_palindrome('bob'))
print(is_palindrome('otto'))
print(is_palindrome('redivider'))```

### 习题6-5 #

aa和 bb 的最大公约数（GCD）是能被二者整除的最大数。

1. 翻译：@theJian
2. 校对：@bingjin
3. 参考：@carfly

## 推荐阅读#

##### bert-serving 模型及源代码#
bert-serving 模型及源代码 提供百度网盘下载。

##### 推荐一个非常优惠的QMT开户渠道#

​Python实用宝典 (pythondict.com)