# Chapter 5 Conditionals and recursion 條件循環
The main topic of this chapter is the if statement, which executes different code depending on the state of the program. But first I want to introduce two new operators: floor division and modulus.
> 本章的主題是if語句,就是條件判斷,會對應程序的不同狀態來執行不同的代碼。但首先我要介紹兩種新的運算符:floor(地板除法,舍棄小數位)和modulus(求模,取余數)
## 5.1 Floor division and modulus 地板除和求模
The floor division operator, //, divides two numbers and rounds down to an integer. For example, suppose the run time of a movie is 105 minutes. You might want to know how long that is in hours. Conventional division returns a floating-point number:
> floor除法,中文有一種翻譯是地板除法,挺難聽,不過湊活了,運算符是兩個右斜杠://,與傳統除法不同,地板除法會把運算結果的小數位舍棄,返回整值。例如,加入一部電影的時間長度是105分鐘。你可能想要知道這部電影用小時來計算是多長。傳統的除法運算如下,會返回一個浮點小數:
```Python
>>> minutes = 105
>>> minutes = 105
>>> minutes / 60
>>> minutes / 60
1.75
```
But we don’t normally write hours with decimal points. Floor division returns the integer number of hours, dropping the fraction part:
> 不過一般咱們不寫有小數的小時數。地板除法返回的就是整的小時數,舍棄掉小數位:
```Python
>>> minutes = 105
>>> minutes = 105
>>> hours = minutes // 60
>>> hours = minutes // 60
>>> hours
>>> hours
1
```
To get the remainder, you could subtract off one hour in minutes:
> 想要知道舍棄那部分的長度,可以用分鐘數減去這么一個小時,然后剩下的分鐘數就是了:
```Python
>>> remainder = minutes - hours * 60
>>> remainder = minutes - hours * 60
>>> remainder
>>> remainder
45
```
An alternative is to use the modulus operator, %, which divides two numbers and returns the remainder.
> 另外一個方法就是使用求模運算符了,百分號%就是了,求模運算就是求余數,會把兩個數相除然后返回余數。
```Python
>>> remainder = minutes % 60
>>> remainder = minutes % 60
>>> remainder
>>> remainder
45
```
The modulus operator is more useful than it seems. For example, you can check whether one number is divisible by another—if x % y is zero, then x is divisible by y.
> 求模運算符的作用遠不止如此。比如你可以用求模來判斷一個數能否被另一個數整除——比如x%y如果等于0了,那就是意味著x能被y整除了。
Also, you can extract the right-most digit or digits from a number. For example, x % 10 yields the right-most digit of x (in base 10). Similarly x % 100yields the last two digits.
> 另外你也可以從一個數上取最右側的一位或多位數字。比如,x%10就會得出x最右邊的數字,也就是x的個位數字。同樣的道理,用x%100得到的就是右面兩位數字了。
If you are using Python 2, division works differently. The division operator, /, performs floor division if both operands are integers, and floating-point division if either operand is a float.
> 如果你用Python2的話,除法是不一樣的。在兩邊都是整形的時候,常規除法運算符/就會進行地板除法,而兩邊只要有一側是浮點數就會進行浮點除法。
## 5.2 Boolean expressions 布爾表達式
A boolean expression is an expression that is either true or false. The following examples use the operator ==, which compares two operands and produces True if they are equal and False otherwise:
> 布爾表達式是一種非對即錯的表達式,只有這么兩個值,true(真)或者false(假)。下面的例子都用了雙等號運算符,這個運算符會判斷兩邊的值是否相等,相等就是True,不相等就是False:
```Python
>>> 5 == 5
>>> 5 == 5
True
>>> 5 == 6
>>> 5 == 6
False
```
True and False are special values that belong to the type bool; they are not strings:
> True和False都是特殊的值,屬于bool布爾類型;它們倆不是字符串:
```Python
>>> type(True)
>>> type(True)
<class 'bool'>
>>> type(False)
>>> type(False)
<class 'bool'>
```
The == operator is one of the relational operators; the others are:
> 雙等號運算符是關系運算符的一種,其他關系運算符如下:
```Python
x != y # x is not equal to y 二者相等
x > y # x is greater than y 前者更大
x > y # x is greater than y 前者更大
x < y # x is less than y 前者更小
x >= y # x is greater than or equal to y 大于等于
x >= y # x is greater than or equal to y 大于等于
x <= y # x is less than or equal to y 小于等于
```
Although these operations are probably familiar to you, the Python symbols are different from the mathematical symbols. A common error is to use a single equal sign (=) instead of a double equal sign (==). Remember that = is an assignment operator and == is a relational operator. There is no such thing as =< or =>.
> 雖然這些運算符你可能很熟悉了,但一定要注意Python里面的符號和數學上的符號有一定區別。常見的錯誤就是混淆了等號=和雙等號==。一定要記住單等號=是一個賦值運算符,而雙等號==是關系運算符。另外要注意就是大于等于或者小于等于都是等號放到大于號或者小于號的后面,順序別弄反。
## 5.3 Logical operators 邏輯運算符
There are three logical operators: and, or, and not. The semantics (meaning) of these operators is similar to their meaning in English. For example, x > 0 and x < 10 is true only if x is greater than 0 and less than 10.
> 邏輯運算符有三種:且,或以及非。這三種運算符的意思和字面意思差不多。比如x>0且x<10,僅當x在0到10之間的時候才為真。
n%2 == 0 or n%3 == 0 is true if either or both of the conditions is true, that is, if the number is divisible by 2 or 3.
> n%2 == 0 或 n%3 == 0,只要條件有一個成立就是真,就是說這個可以被2或3整除就行了。
Finally, the not operator negates a boolean expression, so not (x > y) is true if x > y is false, that is, if x is less than or equal to y.
> 最后說這個非運算,是針對布爾表達式的,非(x>y)為真,那么x>y就是假的,意味著x小于等于y。
Strictly speaking, the operands of the logical operators should be boolean expressions, but Python is not very strict. Any nonzero number is interpreted as True:
> 嚴格來說,邏輯運算符的運算對象應該必須是布爾表達式,不過Python就不太嚴格。任何非零變量都會被認為是真:
```Python
>>> 42 and True
>>> 42 and True
True
```
This flexibility can be useful, but there are some subtleties to it that might be confusing. You might want to avoid it (unless you know what you are doing).
> 這種靈活性特別有用,不過有的情況下也容易引起混淆。建議你盡量不要這樣用,除非你很熟練了。
## 5.4 Conditional execution 條件執行
In order to write useful programs, we almost always need the ability to check conditions and change the behavior of the program accordingly.Conditional statements give us this ability. The simplest form is the if statement:
> 有用的程序必然要有條件檢查判斷的功能,根據不同條件要讓程序有相應的行為。條件語句就讓咱們能夠實現這種判斷。最簡單的就是if語句了:
```Python
if x > 0:
print('x is positive')
```
The boolean expression after if is called the condition. If it is true, the indented statement runs. If not, nothing happens.
> if后面的布爾表達式就叫做條件。如果條件為真,隨后縮進的語句就運行。如果條件為假,就不運行。
if statements have the same structure as function definitions: a header followed by an indented body. Statements like this are called compound statements.
> if語句與函數定義的結構基本一樣:一個頭部,后面跟著縮進的語句。這樣的語句叫做復合語句。
There is no limit on the number of statements that can appear in the body, but there has to be at least one. Occasionally, it is useful to have a body with no statements (usually as a place keeper for code you haven’t written yet). In that case, you can use the pass statement, which does nothing.
> 復合語句中語句體內的語句數量是不限制的,但至少要有一個。有的時候會遇到一個語句體內不放語句的情況,比如空出來用來后續補充。這種情況下,你就可以用pass語句,就是啥也不會做的。
```Python
if x < 0:
pass # TODO: need to handle negative values!
```
## 5.5 Alternative execution 選擇執行
A second form of the if statement is “alternative execution”, in which there are two possibilities and the condition determines which one runs. The syntax looks like this:
> if語句的第二種形式就是『選擇執行』,這種情況下會存在兩種備選的語句,根據條件來判斷執行哪一個。語法如下所示:
```Python
if x % 2 == 0:
print('x is even')
else:
print('x is odd')
```
If the remainder when x is divided by 2 is 0, then we know that x is even, and the program displays an appropriate message. If the condition is false, the second set of statements runs. Since the condition must be true or false, exactly one of the alternatives will run. The alternatives are called branches, because they are branches in the flow of execution.
> 如果x除以2的余數為0,x就是一個偶數了,程序就會顯示對應的信息。如果條件不成立,那就運行第二條語句。這里條件非真即假,只有兩個選擇。這些選擇也叫『分支』,因為在運行流程上產生了不同的分支。
## 5.6 Chained conditionals 鏈式條件
Sometimes there are more than two possibilities and we need more than two branches. One way to express a computation like that is a chained conditional:
> 有時我們要面對的可能性不只有兩種,需要更多的分支。這時候可以使用連鎖條件來實現:
```Python
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 is an abbreviation of “else if”. Again, exactly one branch will run. There is no limit on the number of elif statements. If there is an else clause, it has to be at the end, but there doesn’t have to be one.
> elif是『else if』的縮寫。這回也還是只會有一個分支的語句會被運行。elif語句的數量是無限制的。如果有else語句的話,這個else語句必須放到整個條件鏈的末尾,不過else語句并不是必須有的。
```Python
if choice == 'a':
draw_a()
elif choice == 'b':
draw_b()
elif choice == 'c':
draw_c()
```
Each condition is checked in order. If the first is false, the next is checked, and so on. If one of them is true, the corresponding branch runs and the statement ends. Even if more than one condition is true, only the first true branch runs.
> 每一個條件都會依次被檢查。如果第一個是假,下一個就會被檢查,依此類推。如果有一個為真了,相應的分支語句就運行了,這些條件判斷的語句就都結束了。如果有一個以上的條件為真,只有先出現的為真的條件所對應的分支語句會運行。
## 5.7 Nested conditionals 嵌套條件
One conditional can also be nested within another. We could have written the example in the previous section like this:
> 一個條件判斷也可以嵌套在另一個條件判斷內。上一節的例子可以改寫成如下:
```Python
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')
```
The outer conditional contains two branches. The first branch contains a simple statement. The second branch contains another if statement, which has two branches of its own. Those two branches are both simple statements, although they could have been conditional statements as well.
> 外部的條件判斷包含兩個分支。第一個分支只有一個簡單的語句。第二個分支包含了另外一重條件判斷,這個內部條件判斷有兩個分支。這兩個分支都是簡單的語句,他們的位置也可以繼續放條件判斷語句的。
Although the indentation of the statements makes the structure apparent,nested conditionals become difficult to read very quickly. It is a good idea to avoid them when you can.
> 雖然語句的縮進會讓代碼結構看著比較清晰明顯,但嵌套的條件語句讀起來還是有點難度。所以建議你如果可以的話,盡量避免使用嵌套的條件判斷。
Logical operators often provide a way to simplify nested conditional statements. For example, we can rewrite the following code using a single conditional:
> 邏輯運算符有時候對簡化嵌套條件判斷很有用。比如下面這個代碼就能改寫成更簡單的版本:
```Python
if 0 < x:
if x < 10:
print('x is a positive single-digit number.')
```
The print statement runs only if we make it past both conditionals, so we can get the same effect with the and operator:
> 上面的例子中,只有兩個條件都滿足了才會運行print語句,所以就用邏輯運算符來實現同樣的效果即可:
```Python
if 0 < x and x < 10:
print('x is a positive single-digit number.')
```
For this kind of condition, Python provides a more concise option:
> 這種條件下,Python提供了更簡潔的表達方法:
```Python
if 0 < x < 10:
print('x is a positive single-digit number.')
```
(譯者注:Python的這種友善度遠遠超過了C和C++,這也是為何我一直建議國內高校用Python取代C++來給本科生和研究生做編程入門課程。)
## 5.8 Recursion 遞歸運算
It is legal for one function to call another; it is also legal for a function to call itself. It may not be obvious why that is a good thing, but it turns out to be one of the most magical things a program can do. For example, look at the following function:
> 一個函數可以去調用另一個函數;函數來調用自己也是允許的。這就是遞歸,是程序最神奇的功能之一,現在可能還不好理解為什么,那么來看看下面這個函數為例:
```Python
def countdown(n):
if n <= 0:
print('Blastoff!')
else:
print(n)
countdown(n-1)
```
If n is 0 or negative, it outputs the word, “Blastoff!” Otherwise, it outputs nand then calls a function named countdown—itself—passing n-1 as an argument.
What happens if we call this function like this?
> 如果n為0或者負數,程序會輸出『Blastoff!』。其他情況下,程序會調用自身來運行,以自身參數n減去1為參數。如果像下面這樣調用這個函數會怎么樣?
```Bash
>>> countdown(3)
>>> countdown(3)
```
The execution of countdown begins with n=3, and since n is greater than 0, it outputs the value 3, and then calls itself...
The execution of countdown begins with n=2, and since n is greater than 0, it outputs the value 2, and then calls itself...
The execution of countdown begins with n=1, and since n is greater than 0, it outputs the value 1, and then calls itself...
The execution of countdown begins with n=0, and since n is not greater than 0, it outputs the word, “Blastoff!” and then returns.
The countdown that got n=1 returns.
The countdown that got n=2 returns.
The countdown that got n=3 returns.
And then you’re back in \_\_main\_\_. So, the total output looks like this:
> 開始時候函數參數n是3,大于0,輸出n的值3,然后調用自身,用n-1也就是2作為參數。。。
接下來的函數參數n是2,大于0,輸出n的值2,然后調用自身,用n-1也就是1作為參數。。。
再往下去函數參數n是1,大于0,輸出n的值1,然后調用自身,用n-1也就是0作為參數。。。
最后這次函數參數n是0,等于0了,輸出『Blastoff!』,然后返回。
n=1的時候的countdown也執行完了,返回。
n=2的時候的countdown也執行完了,返回。
n=3的時候的countdown也執行完了,返回。
(譯者注:這時候一定要注意不是輸出字符串就完畢了,要返回的每一個層次的函數調用者。這里不理解的話說明對函數調用的過程掌握的不透徹,一定要好好想仔細了。)
接下來你就回到主函數\_\_main\_\_里面了。所以總的輸出會如下所示:
```Bash
3
2
1
Blastoff!
```
A function that calls itself is recursive; the process of executing it is called recursion.
> 調用自身的函數就是遞歸的;執行這種函數的過程就叫遞歸運算。
As another example, we can write a function that prints a string n times.
> 我們再寫一個用print把一個字符串s顯示n次的例子:
```Python
def print_n(s, n):
if n <= 0:
return
print(s)
print_n(s, n-1)
s="Python is good"
n=4
print_n(s, n)
```
If n <= 0 the return statement exits the function. The flow of execution immediately returns to the caller, and the remaining lines of the function don’t run.
> 如果n小于等于0了,返回語句return就會終止函數的運行。運行流程立即返回到函數調用者,函數其余各行的代碼也都不會執行。
The rest of the function is similar to countdown: it displays s and then calls itself to display s n?1 additional times. So the number of lines of output is 1 + (n - 1), which adds up to n.
> 函數其余部分的代碼很容易理解:print一下s,然后調用自身,用n-1做參數來繼續運行,這樣就額外對s進行了n-1次的顯示。所以輸出的行數是1+(n-1),最終一共有n行輸出。
For simple examples like this, it is probably easier to use a for loop. But we will see examples later that are hard to write with a for loop and easy to write with recursion, so it is good to start early.
> 上面這種簡單的例子,實際上用for循環更簡單。不過后面我們就會遇到一些用for循環不太好寫的例子了,這些情況往往用遞歸更簡單,所以早點學習下遞歸是有好處的。
## 5.9 Stack diagrams for recursive functions 遞歸函數的棧圖
In Section 3.9, we used a stack diagram to represent the state of a program during a function call. The same kind of diagram can help interpret a recursive function.
> 在本書的第三章第九節,我們用棧圖來表征函數調用過程中程序的狀態。同樣是這種棧圖,將有助于給大家展示遞歸函數的運行過程。
Every time a function gets called, Python creates a frame to contain the function’s local variables and parameters. For a recursive function, there might be more than one frame on the stack at the same time.
Figure 5.1 shows a stack diagram for countdown called with n = 3.
> 每次有一個函數被調用的時候,Python都會創建一個框架來包含這個函數的局部變量和形式參數。對于遞歸函數來說,可能會在棧中同時生成多層次的框架。
> 圖5.1展示了前面樣例中coundown函數在n=3的時候的棧圖。
* * *

Figure 5.1: Stack diagram.
* * *
As usual, the top of the stack is the frame for \_\_main\_\_. It is empty because we did not create any variables in \_\_main\_\_ or pass any arguments to it.
> 棧圖的開頭依然是主函數\_\_main\_\_。這里主函數是空的,因為我們沒有在主函數里面創建變量或者傳遞參數進去。
The four countdown frames have different values for the parameter n. The bottom of the stack, where n=0, is called the base case. It does not make a recursive call, so there are no more frames.
> 四個coundown方框中形式參數n的值都是不同的。在棧圖底部是n=0的時候,也叫基準條件。這時候不再進行遞歸調用,也就沒有更多框架了。
As an exercise, draw a stack diagram for print_n called with s = 'Hello' and n=2. Then write a function called do_n that takes a function object and a number, n, as arguments, and that calls the given function n times.
> 下面練習一下,畫一個print_n函數的棧圖,讓s為字符串『Hello』,n為2。然后寫一個函數,名字為do_n,使用一個操作對象和一個數字n作為實際參數,給出一個n作為次數來調用這個函數。
## 5.10 Infinite recursion 無窮遞歸
If a recursion never reaches a base case, it goes on making recursive calls forever, and the program never terminates. This is known as infinite recursion, and it is generally not a good idea. Here is a minimal program with an infinite recursion:
> 如果一個遞歸一直都不能到達基準條件,那就會持續不斷地進行自我調用,程序也就永遠不會終止了。這就叫無窮遞歸,一般這都不是個好事情哈。下面就是一個無窮遞歸的最簡單的例子:
```Python
def recurse():
recurse()
```
In most programming environments, a program with infinite recursion does not really run forever. Python reports an error message when the maximum recursion depth is reached:
> 在大多數的開發環境下,無窮遞歸的程序并不會真的永遠運行下去。Python會在函數達到允許遞歸的最大層次后返回一個錯誤信息:
```Bash
File "<stdin>", line 2, in recurse
File "<stdin>", line 2, in recurse
File "<stdin>", line 2, in recurse
File "<stdin>", line 2, in recurse
RuntimeError: Maximum recursion depth exceeded
```
This traceback is a little bigger than the one we saw in the previous chapter. When the error occurs, there are 1000 recurse frames on the stack!
> 這個追蹤會我們之前看到的長很多。這種錯誤出現的時候,棧中都已經有1000層遞歸框架了!
If you write encounter an infinite recursion by accident, review your function to confirm that there is a base case that does not make a recursive call. And if there is a base case, check whether you are guaranteed to reach it.
> 如果你意外寫出來一個無窮遞歸的代碼,好好檢查一下你的函數,一定要確保有一個基準條件來停止遞歸調用。如果存在了基準條件,檢查一下一定要確保能使之成立。
## 5.11 Keyboard input 鍵盤輸入
The programs we have written so far accept no input from the user. They just do the same thing every time.
> 目前為止咱們寫過的程序還都沒有接收過用戶的輸入。這寫程序每次都是做一些同樣的事情。
Python provides a built-in function called input that stops the program and waits for the user to type something. When the user presses Return or Enter, the program resumes and input returns what the user typed as a string. In Python 2, the same function is called raw_input.
> Python提供了內置的一個函數,名叫input,這個函數會停止程序運行,等待用戶來輸入一些內容。用戶按下ESC或者Enter回車鍵,程序就恢復運行,input函數就把用戶輸入的內容作為字符串返回。在Python2里面,同樣的函數名字不同,叫做raw_input。
```Bash
>>> text = input()
>>> text = input()
What are you waiting for?
>>> text
>>> text
What are you waiting for?
```
Before getting input from the user, it is a good idea to print a prompt telling the user what to type. input can take a prompt as an argument:
> 在用戶輸入內容之前,最好顯示一些提示,來告訴用戶需要輸入什么內容。input函數能夠把提示內容作為參數:
```Bash
>>> name = input('What...is your name?\n')
>>> name = input('What...is your name?\n')
What...is your name?
Arthur, King of the Britons!
>>> name
>>> name
Arthur, King of the Britons!
```
The sequence \n at the end of the prompt represents a newline, which is a special character that causes a line break. That’s why the user’s input appears below the prompt.
> 提示內容末尾的\n表示要新建一行,這是一個特殊的字符,表示換行。因為有了換行字符,所以用戶輸入就跑到了提示內容下面去了。
If you expect the user to type an integer, you can try to convert the return value to int:
> 如果你想要用戶來輸入一個整形變量,可以把返回的值手動轉換一下:
```Bash
>>> prompt = 'What...is the airspeed velocity of an unladen swallow?\n'
>>> 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?
42
>>> int(speed)
>>> int(speed)
42
```
But if the user types something other than a string of digits, you get an error:
> 如果用戶輸入的是其他內容,而不是一串數字,就會得到一個錯誤了:
```Python
>>> 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?
>>> int(speed) ValueError: invalid literal for int() with base 10
>>> int(speed) ValueError: invalid literal for int() with base 10
```
We will see how to handle this kind of error later.
> 稍后我們再來看看如何應對這種錯誤。
## 5.12 Debugging 調試
When a syntax or runtime error occurs, the error message contains a lot of information, but it can be overwhelming. The most useful parts are usually:
> 當語法錯誤或者運行錯誤出現的時候,錯誤信息會包含很多有用的信息,不過信息量太大,太繁雜。最有用的也就下面這兩類:
* What kind of error it was, and
> 錯誤的類型是什么,以及
* Where it occurred.
> 錯誤的位置在哪里。
Syntax errors are usually easy to find, but there are a few gotchas. Whitespace errors can be tricky because spaces and tabs are invisible and we are used to ignoring them.
```Bash
>>> x = 5
>>> x = 5
>>> y = 6
>>> y = 6
File "<stdin>", line 1
y = 6
^
IndentationError: unexpected indent
```
In this example, the problem is that the second line is indented by one space. But the error message points to y, which is misleading. In general, error messages indicate where the problem was discovered, but the actual error might be earlier in the code, sometimes on a previous line.
> 這個例子里面,錯誤的地方是第二行開頭用一個空格來縮進了。但這個錯誤是指向y的,這就有點誤導了。一般情況下,錯誤信息都會表示出發現問題的位置,但具體的錯誤可能是在此位置之前的代碼引起的,有的時候甚至是前一行。
The same is true of runtime errors. Suppose you are trying to compute a signal-to-noise ratio in decibels. The formula is

In Python, you might write something like this:
> 同樣情況也發生在運行錯誤的情況下。假設你試著用分貝為單位來計算信噪比。
公式為:

> 在Python,你可能像下面這樣寫:
```Python
import math
signal_power = 9
noise_power = 10
ratio = signal_power // noise_power
decibels = 10 * math.log10(ratio) print(decibels)
```
When you run this program, you get an exception:
> 運行這個程序,你就會得到如下錯誤信息:
```Bash
Traceback (most recent call last):
File "snr.py", line 5, in ?
decibels = 10 * math.log10(ratio)
ValueError: math domain error
```
The error message indicates line 5, but there is nothing wrong with that line. To find the real error, it might be useful to print the value of ratio, which turns out to be 0. The problem is in line 4, which uses floor division instead of floating-point division.
> 這個錯誤信息提示第五行,但那一行實際上并沒有錯。要找到真正的錯誤,就要輸出一下ratio的值來看一下,結果發現是0了。那問題實際是在第四行,應該用浮點除法,結果多打了一個右斜杠,弄成了地板除法,才導致的錯誤。
You should take the time to read error messages carefully, but don’t assume that everything they say is correct.
> 所以你得花點時間仔細閱讀錯誤信息,但不要輕易就認為出錯信息說的內容都是完全正確可靠的。
## 5.13 Glossary 術語列表
floor division:
An operator, denoted //, that divides two numbers and rounds down (toward zero) to an integer.
> 地板除法:一種運算符,雙右斜杠,把兩個數相除,舍棄小數位,結果為整形。
modulus operator:
An operator, denoted with a percent sign (%), that works on integers and returns the remainder when one number is divided by another.
> 求模取余:一種運算符,百分號%,對整形起作用,返回兩個數字相除的余數。
boolean expression:
An expression whose value is either True or False.
> 布爾表達式:一種值為真或假的表達式。
relational operator:
One of the operators that compares its operands: ==, !=, >, <, >=, and <=.
> 關系運算符:對比運算對象關系的運算符:==相等, !=不等, >大于, <小于, >=大于等于, 以及<=小于等于。
logical operator:
One of the operators that combines boolean expressions: and, or, and not.
> 邏輯運算符:把布爾表達式連接起來的運算符:and且,or或,以及not非。
conditional statement:
A statement that controls the flow of execution depending on some condition.
> 條件語句:控制運行流程的語句,根據不同條件有不同語句去運行。
condition:
The boolean expression in a conditional statement that determines which branch runs.
> 條件:條件語句所適用的布爾表達式,根據真假來決定運行分支。
compound statement:
A statement that consists of a header and a body. The header ends with a colon (:). The body is indented relative to the header.
> 復合語句:包含頭部與語句體的一套語句組合。頭部要有冒號做結尾,語句體相對于頭部要有一次縮進。
branch:
One of the alternative sequences of statements in a conditional statement.
> 分支:條件語句當中備選的一系列語句。
chained conditional:
A conditional statement with a series of alternative branches.
> 鏈式條件:一系列可選分支構成的條件語句。
nested conditional:
A conditional statement that appears in one of the branches of another conditional statement.
> 嵌套條件:條件語句分支中繼續包含次級條件語句的情況。
return statement:
A statement that causes a function to end immediately and return to the caller.
> 返回語句:一種特殊的語句,功能是終止當前函數,立即跳出到函數調用者。
recursion:
The process of calling the function that is currently executing.
> 遞歸:函數對自身進行調用的過程。
base case:
A conditional branch in a recursive function that does not make a recursive call.
> 基準條件:遞歸函數中一個條件分支,要實現終止遞歸調用。
infinite recursion:
A recursion that doesn’t have a base case, or never reaches it. Eventually, an infinite recursion causes a runtime error.
> 無窮遞歸:一個沒有基準條件的遞歸,或者永遠無法達到基準條件的遞歸。一般無窮遞歸總會引起運行錯誤。
## 5.14 Exercises 練習
### Exercise 1 練習1
The time module provides a function, also named time, that returns the current Greenwich Mean Time in “the epoch”, which is an arbitrary time used as a reference point. On UNIX systems, the epoch is 1 January 1970.
> time模塊提供了一個名字同樣叫做time的函數,會返回當前格林威治時間的時間戳,就是以某一個時間點作為初始參考值。在Unix系統中,時間戳的參考值是1970年1月1號。
> (譯者注:時間戳就是系統當前時間相對于1970.1.1 00:00:00以秒計算的偏移量,時間戳是惟一的。)
```Bash
>>> import time
>>> import time
>>> time.time() 1437746094.5735958
>>> time.time() 1437746094.5735958
```
Write a script that reads the current time and converts it to a time of day in hours, minutes, and seconds, plus the number of days since the epoch.
> 寫一個腳本,讀取當前的時間,把這個時間轉換以天為單位,剩余部分轉換成小時-分鐘-秒的形式,加上參考時間以來的天數。
### Exercise 2 練習2
Fermat’s Last Theorem says that there are no positive integers a, b, and c such that

for any values of n greater than 2.
> 費馬大定理內容為,a、b、c、n均為正整數,在n大于2的情況,下面的等式關系不成立:
> 
1. Write a function named check_fermat that takes four parameters—a, b, c and n—and checks to see if Fermat’s theorem holds. If n is greater than 2 and
> 寫一個函數,名叫check_fermat,這個函數有四個形式參數:a、b、c以及n,檢查一下費馬大定理是否成立,看看在n大于2的情況下下列等式
> 
> 是否成立。
2. The program should print, “Holy smokes, Fermat was wrong!” Otherwise the program should print, “No, that doesn’t work.”
> 要求程序輸出『Holy smokes, Fermat was wrong!』或者『No, that doesn’t work.』
3. Write a function that prompts the user to input values for a, b, c and n, converts them to integers, and uses check_fermat to check whether they violate Fermat’s theorem.
> 寫一個函數來提醒用戶要輸入a、b、c和n的值,然后把輸入值轉換為整形變量,接著用check_fermat這個函數來檢查他們是否違背了費馬大定理。
### Exercise 3 練習3
If you are given three sticks, you may or may not be able to arrange them in a triangle. For example, if one of the sticks is 12 inches long and the other two are one inch long, you will not be able to get the short sticks to meet in the middle. For any three lengths, there is a simple test to see if it is possible to form a triangle:
> 給你三根木棍,你能不能把它們拼成三角形呢?比如一個木棍是12英寸長,另外兩個是1英寸長,這兩根短的就不夠長,無法拼成三角形了。
> (譯者注:1英寸=2.54厘米)對于任意的三個長度,有一個簡單的方法來檢測它們能否拼成三角形:
If any of the three lengths is greater than the sum of the other two, then you cannot form a triangle. Otherwise, you can. (If the sum of two lengths equals the third, they form what is called a “degenerate” triangle.)
> 只要三個木棍中有任意一個的長度大于其他兩個的和,就拼不成三角形了。必須要任意一個長度都小于兩邊和才能拼成三角形。(如果兩邊長等于第三邊,就只能組成所謂『退化三角形』了。譯者注:實際上這不就成了線段了么?)
1. Write a function named is_triangle that takes three integers as arguments, and that prints either “Yes” or “No”, depending on whether you can or cannot form a triangle from sticks with the given lengths.
> 寫一個叫做is_triangle的函數,用三個整形變量為實際參數,函數根據你輸入的值能否拼成三角形來判斷輸出『Yes』或者『No』。
2. Write a function that prompts the user to input three stick lengths, converts them to integers, and uses is_triangle to check whether sticks with the given lengths can form a triangle.
> 寫一個函數來提示下用戶,要輸入三遍長度,把它們轉換成整形,用is_triangle函數來檢測這些給定長度的邊能否組成三角形。
### Exercise 4 練習4
What is the output of the following program? Draw a stack diagram that shows the state of the program when it prints the result.
> 下面的代碼輸出會是什么?畫一個棧圖來表示一下如下例子中程序輸出結果時候的狀態。
```Python
def recurse(n, s):
if n == 0:
print(s)
else:
recurse(n-1, n+s)
recurse(3, 0)
```
1. What would happen if you called this function like this: recurse(-1, 0)?
> recurse(-1, 0)這樣的調用函數會有什么效果?
2. Write a docstring that explains everything someone would need to know in order to use this function (and nothing else).
> 為這個函數寫一個文檔字符串,解釋一下用法(僅此而已)。
The following exercises use the turtle module, described in Chapter 4:
> 接下來的練習用到了第四章我們提到過的turtle小烏龜模塊。
### Exercise 5 練習5
Read the following function and see if you can figure out what it does. Then run it (see the examples in Chapter 4).
> 閱讀下面的函數,看看你能否弄清楚函數的作用。運行一下試試(參考第四章里面的例子來酌情修改代碼)。
```Python
def draw(t, length, n):
if n == 0:
return
angle = 50
t.fd(length*n)
t.lt(angle)
draw(t, length, n-1)
t.rt(2*angle)
draw(t, length, n-1)
t.lt(angle)
t.bk(length*n)
```
* * *

Figure 5.2: A Koch curve.
* * *
### Exercise 6 練習6
The Koch curve is a fractal that looks something like Figure 5.2. To draw a Koch curve with length x, all you have to do is
> Koch科赫曲線是一種分形曲線,外觀如圖5.2所示。要畫長度為x的這種曲線,你要做的步驟如下:
1. Draw a Koch curve with length x/3.
> 畫一個長度為三分之一x的Koch曲線。
2. Turn left 60 degrees.
> 左轉60度。
3. Draw a Koch curve with length x/3.
> 畫一個長度為三分之一x的Koch曲線。
4. Turn right 120 degrees.
> 右轉120度。
5. Draw a Koch curve with length x/3.
> 畫一個長度為三分之一x的Koch曲線。
6. Turn left 60 degrees.
> 左轉60度。
7. Draw a Koch curve with length x/3.
> 畫一個長度為三分之一x的Koch曲線。
The exception is if x is less than 3: in that case, you can just draw a straight line with length x.
> 特例是當x小于3的時候:這種情況下,你就可以只畫一個長度為x的直線段。
1. Write a function called koch that takes a turtle and a length as parameters, and that uses the turtle to draw a Koch curve with the given length.
> 寫一個叫做koch的函數,用一個小烏龜turtle以及一個長度length做形式參數,用這個小烏龜來畫給定長度length的Koch曲線。
2. Write a function called snowflake that draws three Koch curves to make the outline of a snowflake.[Solution](http://thinkpython2.com/code/koch.py).
> 寫一個叫做snowflake的函數,畫三個Koch曲線來制作一個雪花的輪廓。[參考代碼](http://thinkpython2.com/code/koch.py)
3. The Koch curve can be generalized in several ways. See [here](http://en.wikipedia.org/wiki/Koch_snowflake) for examples and implement your favorite.
> 生成Koch曲線的方法還有很多。點擊 [這里](http://en.wikipedia.org/wiki/Koch_snowflake)來查看更多的例子,探索一下看看你喜歡哪個。
- 介紹
- Think Python
- Chapter 0 Preface 前言
- Chapter 1 The way of the program 編程之路
- Chapter 2 Variables, expressions and statements 變量,表達式,語句
- Chapter 3 Functions 函數
- Chapter 4 Case study: interface design 案例學習:交互設計
- Chapter 5 Conditionals and recursion 條件循環
- Chapter 6 Fruitful functions 有返回值的函數
- Chapter 7 Iteration 迭代
- Chapter 8 Strings 字符串
- Chapter 9 Case study: word play 案例學習:單詞游戲
- Chapter 10 Lists 列表
- Chapter 11 Dictionaries 字典
- Chapter 12 Tuples 元組
- Chapter 13 Case study: data structure selection 案例學習:數據結構的選擇
- Chapter 14 Files 文件
- Chapter 15 Classes and objects 類和對象
- Chapter 16 Classes and functions 類和函數
- Chapter 17 Classes and methods 類和方法
- Chapter 18 Inheritance 繼承
- Chapter 19 The Goodies 額外補充