# 用Python编程 笔记2

### 第四章 条件和递归（Conditionals and recursion）

#### 4.1 模除运算符(modulus operator)

>>> quotient = 7 / 3
>>> print quotient
2

>>> remainder = 7 % 3
>>> print remainder
1

#### 4.2 布尔表示法(Boolean expressions)

>>> 5 == 5
True
>>> 5 == 6
False

• x != y # x不等于y
• x > y # x大于y
• x < y # x小于y
• x >= y # x大于等于y
• x <= y # x小于等于y

#### 4.4 执行条件（Conditional execution）

 1 2 `if` `x > ``0``;` `  ``print` `"x is positive"`

#### 4.5 选择执行（Alternative execution）

 1 2 3 4 `if` `x``%``2` `=``=` `0``:` `  ``print` `x, ``"is even"` `else``:` `  ``print` `x, ``"is odd"`

 1 2 3 4 5 `def` `printParity(x):` `  ``if` `x``%``2` `=``=` `0``:` `    ``print` `x, ``"is even"` `  ``else``:` `    ``print` `x, ``"is odd"`

#### 4.6 链接条件（Chained conditionals）

 1 2 3 4 5 6 `if` `x < y:` `  ``print` `x, ``"is less than"``, y` `elif` `x > y:` `  ``print` `x, ``"is greater than"``, y` `else``:` `  ``print` `x, ``"and"``, y, ``"are equal"`

elif是else if的缩写

#### 4.7 条件嵌套（Nested conditionals）

 1 2 3 4 5 6 7 `if` `x ``=``=` `y:` `  ``print` `x, ``"and"``, y, ``"are equal"` `else``:` `  ``if` `x < y:` `    ``print` `x, ``"is less than"``, y` `  ``else``:` `    ``print` `x, ``"is greater than"``, y`

if语句是一个布尔函数，可以使用复杂的条件判断

 1 2 `if` `0` `< x < ``10``:` `  ``print` `"x is a positive single digit."`

#### 4.8 返回语句（The return statement）

 1 2 3 4 5 6 7 8 9 `import` `math` `def` `printLogarithm(x):` `  ``if` `x <``=` `0``:` `    ``print` `"Positive numbers only, please."` `  ``return` `result ``=` `math.log(x)` `print` `"The log of x is"``, result`

#### 4.9 递归（Recursion）

 1 2 3 4 5 6 `def` `countdown(n):` `  ``if` `n ``=``=` `0``:` `    ``print` `"Blastoff!"` `  ``else``:` `    ``print` `n` `    ``countdown(n``-``1``)`

>>> countdown(3)
3
2
1
Blastoff!

 1 2 3 4 `def` `nLines(n):` `  ``if` `n > ``0``:` `    ``print` `    ``nLines(n``-``1``)`

#### 4.11 无限递归(Infinite recursion)

Python中无限递归并不能无限进行下去，而是在达到了递归的最大限制数量之后停止运行并且报错：

File “<stdin>”, line 2, in recurse
(98 repetitions omitted)
File “<stdin>”, line 2, in recurse
RuntimeError: Maximum recursion depth exceeded

#### 4.12 键盘输入（Keyboard input）

Python提供自带的取得用户键盘输入的函数，叫 raw_input 当这个函数被调用后，程序会停止运行并且等待用户输入

>>> name = raw_input (“What…is your name? “)
What…is your name? Arthur, King of the Britons!
>>> print name
Arthur, King of the Britons!

prompt = “What…is the airspeed velocity of an unladen swallow?n”
speed = input(prompt)

>>> speed = input (prompt)
What…is the airspeed velocity of an unladen swallow?
What do you mean, an African or a European swallow?
SyntaxError: invalid syntax

### 第五章 卓有成效的功能（Fruitful functions）

#### 5.1 返回值（Return values）

 1 2 `e ``=` `math.exp(``1.0``)` `height ``=` `radius ``*` `math.sin(angle)`

 1 2 3 4 `import` `math` `def` `area(radius):` `  ``temp ``=` `math.pi ``*` `radius``*``*``2` `  ``return` `temp`

temp这个变量只存在于函数中，对函数之外没有意义，可以如下编写来跳过temp

 1 2 3 `import` `math` `def` `area(radius):` `  ``return` `math.pi ``*` `radius``*``*``2`

 1 2 3 4 5 `def` `absoluteValue(x):` `  ``if` `x < ``0``:` `    ``return` `-``x` `  ``elif` `x > ``0``:` `    ``return` `x`

>>> print absoluteValue(0)
None

### 5.2程序开发

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

 1 2 3 4 5 6 `def` `distance(x1, y1, x2, y2):` `  ``dx ``=` `x2 ``-` `x1` `  ``dy ``=` `y2 ``-` `y1` `  ``print` `"dx is"``, dx` `  ``print` `"dy is"``, dy` `  ``return` `0.0`

 1 2 3 4 5 6 `def` `distance(x1, y1, x2, y2):` `  ``dx ``=` `x2 ``-` `x1` `  ``dy ``=` `y2 ``-` `y1` `  ``dsquared ``=` `dx``*``*``2` `+` `dy``*``*``2` `  ``print` `"dsquared is: "``, dsquared` `  ``return` `0.0`

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

#### 5.3组合(Composition)

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

 1 2 `result ``=` `area(radius)` `return` `result`

 1 2 3 4 `def` `area2(xc, yc, xp, yp):` `  ``radius ``=` `distance(xc, yc, xp, yp)` `  ``result ``=` `area(radius)` `  ``return` `result`

 1 2 `def` `area2(xc, yc, xp, yp):` `  ``return` `area(distance(xc, yc, xp, yp))`

#### 5.4布尔函数（Bollean functions）

 1 2 3 4 5 `def` `isDivisible(x, y):` `  ``if` `x ``%` `y ``=``=` `0``:` `    ``return` `True` `  ``else``:` `    ``return` `False`

 1 2 `def` `isDivisible(x, y):` `  ``return` `x ``%` `y ``=``=` `0`

#### 5.5更多递归（More recursion）

frabjuous: An adjective used to describe something that is frabjuous.

0! = 1

n! = n(n − 1)!

 1 2 3 4 5 6 7 `def` `factorial(n):` `  ``if` `n ``=``=` `0``:` `    ``return` `1` `  ``else``:` `    ``recurse ``=` `factorial(n``-``1``)` `    ``result ``=` `n ``*` `recurse` `    ``return` `result`

 1 2 3 4 5 `def` `factorial(n):` `  ``if` `n ``=``=` `0``:` `    ``return` `1` `  ``else``:` `    ``return` `n ``*` `factorial(n``-``1``)`

#### 5.7 另一个例子

 1 2 3 4 5 `def` `fibonacci (n):` `  ``if` `n ``=``=` `0` `or` `n ``=``=` `1``:` `    ``return` `1` `  ``else``:` `    ``return` `fibonacci(n``-``1``) ``+` `fibonacci(n``-``2``)`

#### 5.8 类型检查

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

 1 2 3 4 5 6 7 8 9 10 11 `def` `factorial (n):` `  ``if` `not` `isinstance``(n, ``int``):` `    ``print` `"Factorial is only defined for integers."` `    ``return` `-``1` `  ``elif` `n < ``0``:` `    ``print` `"Factorial is only defined for positive integers."` `    ``return` `-``1` `  ``elif` `n ``=``=` `0``:` `    ``return` `1` `  ``else``:` `    ``return` `n ``*` `factorial(n``-``1``)`

### 第六章 迭代（Iteration）

#### 6.2 While语句

 1 2 3 4 5 `def` `countdown(n):` `  ``while` `n > ``0``:` `    ``print` `n` `    ``n ``=` `n``-``1` `  ``print` `"Blastoff!"`

#### 6.3表格Tables

 1 2 3 4 `x ``=` `1.0` `while` `x < ``10.0``:` `  ``print` `x, ’t’, math.log(x)` `  ``x ``=` `x ``+` `1.0`

‘t’代表一个tab符号，’n代表新的一行’

1.0      0.0
2.0      0.69314718056
3.0      1.09861228867
4.0      1.38629436112
5.0      1.60943791243
6.0      1.79175946923
7.0      1.94591014906
8.0      2.07944154168
9.0      2.19722457734

 1 2 3 4 `x ``=` `1.0` `while` `x < ``100.0``:` `  ``print` `x, ’t’, math.log(x)``/``math.log(``2.0``)` `  ``x ``=` `x ``*` `2.0`

1.0      0.0
2.0      1.0
4.0      2.0
8.0      3.0
16.0    4.0
32.0    5.0
64.0    6.0

#### 6.4 二维表格

 1 2 3 4 5 `i ``=` `1` `while` `i <``=` `6``:` `  ``print` `2``*``i, ’ ’,` `  ``i ``=` `i ``+` `1` `print`

2      4      6      8      10      12

#### 6.5 封装和扩展（Encapsulation and generalization）

 1 2 3 4 5 6 `def` `printMultiples(n):` `  ``i ``=` `1` `  ``while` `i <``=` `6``:` `    ``print` `n``*``i, ’t’,` `    ``i ``=` `i ``+` `1` `  ``print`

3      6      9      12      15      18

 1 2 3 4 `i ``=` `1` `while` `i <``=` `6``:` `  ``printMultiples(i)` `  ``i ``=` `i ``+` `1`

1      2      3      4      5      6
2      4      6      8      10    12
3      6      9      12    15    18
4      8      12    16    20    24
5      10    15    20    25    30
6      12    18    24    30    36

#### 6.6更多封装（More encapsulation）

 1 2 3 4 5 `def` `printMultTable():` `  ``i ``=` `1` `  ``while` `i <``=` `6``:` `    ``printMultiples(i)` `    ``i ``=` `i ``+` `1`

#### 6.8更多扩展

 1 2 3 4 5 `def` `printMulTable(high):` `  ``i ``=` `1` `    ``while` `i <``=` `high:` `    ``printMiultiples(i)` `    ``i ``=` `i ``+` `1`

1      2      3      4      5      6
2      4      6      8      10    12
3      6      9      12    15    18
4      8      12    16    20    24
5      10    15    20    25    30
6      12    18    24    30    36
7      14    21    28    35    42

 1 2 3 4 5 6 7 8 9 10 11 `def` `printMultiples(n, high):` `  ``i ``=` `1` `  ``while` `i <``=` `high:` `    ``print` `n``*``i, ’t’,` `    ``i ``=` `i ``+` `1` `  ``print` `def` `printMultTable(high):` `  ``i ``=` `1` `  ``while` `i <``=` `high:` `    ``printMultiples(i, high)` `    ``i ``=` `i ``+` `1`

 1 `printMultiples(i, high)`

 1 `printMultiples(i, i)`

1
2      4
3      6      9
4      8      12    16
5      10    15    20    25
6      12    18    24    30    36
7      14    21    28    35    42   49

#### 6.9函数(Functions)

1. 将一系列语句封装起来，并赋予名称，便于阅读和调试
2. 将一个长的程序拆解成不同的部分，将一个个独立的函数单独调试，然后再合成一个完整程序
3. 使用函数可以促进递归和迭代
4. 良好设计的函数可以为很多程序所用，可重用

How to Think Like a Computer Scientist
Learning with Python

by Allen Downey, Jeff Elkner and Chris Meyers.