# Chapter 2 Variables, expressions and statements 變量,表達式,語句
One of the most powerful features of a programming language is the ability to manipulate variables. A variable is a name that refers to a value.
> 編程語言最強大的功能就是操作變量。變量就是一個有值的代號。
## 2.1 Assignment statements 賦值語句
An assignment statement creates a new variable and gives it a value:
> 賦值語句的作用是創建一個新的變量,并且賦值給這個變量:
```python
>>> message = 'And now for something completely different'
>>> message = 'And now for something completely different'
>>> n = 17
>>> n = 17
>>> pi = 3.141592653589793
>>> pi = 3.141592653589793
```
This example makes three assignments. The first assigns a string to a new variable named message; the second gives the integer 17 to n; the third assigns the (approximate) value of π to pi.
> 上面就是三個賦值語句的例子。第一個是把一個字符串復制給名叫message的新變量;第二個將n賦值為整數17;第三個把圓周率的一個近似值賦給了pi這個變量。
A common way to represent variables on paper is to write the name with an arrow pointing to its value. This kind of figure is called a state diagram because it shows what state each of the variables is in (think of it as the variable’s state of mind). Figure 2.1 shows the result of the previous example.
> 平常大家在紙上對變量賦值的方法就是寫下名字,然后一個箭頭指向它的值。這種圖解叫做狀態圖,因為它能指明各個變量存儲的是什么內容。下圖就展示了上面例子中賦值語句的結果。
* * *

Figure 2.1: State diagram.
* * *
## 2.2 Variable names 變量名稱
Programmers generally choose names for their variables that are meaningful—they document what the variable is used for.
> 編程的人總得給變量起個有一定意義的名字才能記得住,一般情況就用名字來表示這個變量的用途了。
Variable names can be as long as you like. They can contain both letters and numbers, but they can’t begin with a number. It is legal to use uppercase letters, but it is conventional to use only lower case for variables names.
> 變量名稱你隨便起多長都可以的。包含字母或者數字都行,但是不能用數字來開頭。大寫字母也能用,不過還是建議都用小寫字母來給變量命名,這個比較傳統哈。
The underscore character, _, can appear in a name. It is often used in names with multiple words, such as your_name or airspeed_of_unladen_swallow.
> 變量名里面可以有下劃線_,一般在多個單詞組成的變量名里面往往用到下劃線,比如your_name等等。
If you give a variable an illegal name, you get a syntax error:
> 你要是給變量起名不合規則,就會出現語法錯誤提示了:
```Python
>>> 76trombones = 'big parade'
>>> 76trombones = 'big parade'
SyntaxError: invalid syntax
>>> more@ = 1000000
>>> more@ = 1000000
SyntaxError: invalid syntax
>>> class = 'Advanced Theoretical Zymurgy'
>>> class = 'Advanced Theoretical Zymurgy'
SyntaxError: invalid syntax
```
76trombones is illegal because it begins with a number. more@ is illegal because it contains an illegal character, @. But what’s wrong with class?
> 第一個數字開頭所以不合規則,第二個有非法字符@,第三個這個class咋不行呢?好奇吧?
It turns out that class is one of Python’s keywords. The interpreter uses keywords to recognize the structure of the program, and they cannot be used as variable names.
> 因為clas是Python里面的一個關鍵詞啦。解釋器要用關鍵詞來識別程序的結構,這些關鍵詞是不能用來做變量名的。
Python 3 has these keywords:
> 以下是Python3的關鍵詞哈:
* False class finally is
* return None continue for lambda
* try True def from nonlocal
* while and del global not
* with as elif if or
* yield assert else import pass
* break except in raise
You don’t have to memorize this list. In most development environments, keywords are displayed in a different color; if you try to use one as a variable name, you’ll know.
> 你不用去記憶這些哈。因為一般大多數的開發環境里面,關鍵詞都會有區別于普通代碼的顏色提示你,你要是用他們做變量名了,一看就會知道的。
## 2.3 Expressions and statements 表達式和語句
An expression is a combination of values, variables, and operators. A value all by itself is considered an expression, and so is a variable, so the following are all legal expressions:
> 表達式是數值,變量和操作符的組合。單個值本身也被當作一個表達式,變量也是如此,下面這些例子都是一些正確表達式:
```Python
>>> 42
>>> 42
42
>>> n
>>> n
17
>>> n + 25
>>> n + 25
42
```
When you type an expression at the prompt, the interpreter evaluates it, which means that it finds the value of the expression. In this example, n has the value 17 and n + 25 has the value 42.
> 當你在提示符后面敲出一個表達式,解釋器就判斷一下,他會找到這個表達式的值。在本節的例子中,n的值是17,所以n+25就是42了。
A statement is a unit of code that has an effect, like creating a variable or displaying a value.
> 語句是一組具有某些效果的代碼,比如創建變量,或者顯示值。
```Python
>>> n = 17
>>> n = 17
>>> print(n)
>>> print(n)
```
The first line is an assignment statement that gives a value to n. The second line is a print statement that displays the value of n.
> 上面第一個就是賦值語句,給n賦值。第二行是顯示n的值。
When you type a statement, the interpreter executes it, which means that it does whatever the statement says. In general, statements don’t have values.
> 輸入語句的時候,解釋器會執行它,就是會按照語句所說的去做。一般語句是沒有值的。
## 2.4 Script mode 腳本模式
So far we have run Python in interactive mode, which means that you interact directly with the interpreter. Interactive mode is a good way to get started, but if you are working with more than a few lines of code, it can be clumsy.
> 以上我們一直在用Python的交互模式,就是直接咱們人跟解釋器來交互。開始學的時候這樣挺好的,但如果你要想一次運行多行代碼,這樣就很不方便了。
The alternative is to save code in a file called a script and then run the interpreter in script mode to execute the script. By convention, Python scripts have names that end with .py.
> 所以就有另一種選擇了,把代碼保存成腳本,然后用腳本模式讓解釋器來運行這些腳本。通常Python腳本文件的擴展名是.py。
If you know how to create and run a script on your computer, you are ready to go. Otherwise I recommend using PythonAnywhere again. I have posted instructions for running in script mode at http://tinyurl.com/thinkpython2e.
> 如果你知道怎么創建和運行腳本,那就盡管在自己電腦上嘗試好了。否則我就建議你還是用PythonAnywhere。關于腳本模式的介紹我放到網上了,打開這個鏈接(http://tinyurl.com/thinkpython2e)去看下哈。
Because Python provides both modes, you can test bits of code in interactive mode before you put them in a script. But there are differences between interactive mode and script mode that can be confusing.
> Python兩種模式都支持,所以你可以先用交互模式做點測試,然后再寫成腳本。但是兩種模式之間有些區別的,所以可能也挺麻煩。
For example, if you are using Python as a calculator, you might type:
舉個例子哈,比如咱們把Python當計算器用,你輸入以下內容:
```Python
>>> miles = 26.2
>>> miles = 26.2
>>> miles * 1.61
>>> miles * 1.61
42.182
```
The first line assigns a value to miles, but it has no visible effect. The second line is an expression, so the interpreter evaluates it and displays the result. It turns out that a marathon is about 42 kilometers.
> 第一行給miles這個變量賦初值(譯者注:26.2英里是馬拉松比賽全程長度),但是看著沒啥效果。第二行是一個表達式,解釋器會計算這個表達式,然后把結果輸出。結果就是把馬拉松全程長度從英里換算成公里,答案是42公里哈。
But if you type the same code into a script and run it, you get no output at all. In script mode an expression, all by itself, has no visible effect. Python actually evaluates the expression, but it doesn’t display the value unless you tell it to:
> 不過你要是直接把這些代碼存成腳本然后運行,是啥都看不到的,沒有輸出。在腳本模式表達式是沒有明顯效果的。Python確實會計算這些表達式,但不顯示結果,想看到結果你就得告訴他輸出一下:
```Python
miles = 26.2
print(miles * 1.61)
```
This behavior can be confusing at first.
> 這種情況開始還挺讓人混亂的。
A script usually contains a sequence of statements. If there is more than one statement, the results appear one at a time as the statements execute.
> 腳本一般都是包含了一系列的語句。如果語句超過一條,每個語句執行的時候都會顯示結果。比如下面這個:
For example, the script
```python
print(1)
x = 2
print(x)
```
produces the output
> 輸出的結果如下
```Python
1
2
```
The assignment statement produces no output.
> 賦值語句是不會有任何輸出的。
To check your understanding, type the following statements in the Python interpreter and see what they do:
> 檢查下你理解了沒哈,把下面這些語句輸入到Python解釋器,看看會發生什么:
```Python
5 x = 5 x + 1
```
Now put the same statements in a script and run it. What is the output? Modify the script by transforming each expression into a print statement and then run it again.
> 現在再把同樣的語句輸入到腳本中,然后用Python來運行一下。看看輸出是啥樣的?把腳本中的表達式修改一下,每一個都加一個打印語句再試試。
## 2.5 Order of operations 運算符優先級
When an expression contains more than one operator, the order of evaluation depends on the order of operations. For mathematical operators, Python follows mathematical convention. The acronym PEMDAS is a useful way to remember the rules:
> 表達式可能會包含不止一個運算符,這些不同的運算先后次序就是運算符的優先級。對于數學運算符來說,Python就遵循著數學上的規則。下面這個PEMDAS、是用來記憶這些優先規則的好方法:
* Parentheses have the highest precedence and can be used to force an expression to evaluate in the order you want. Since expressions in parentheses are evaluated first, 2 * (3-1) is 4, and (1+1)**(5-2) is 8. You can also use parentheses to make an expression easier to read, as in(minute * 100) / 60, even if it doesn’t change the result.
> 括號內的內容最優先,大家可以用括號來強制某系表達式有限計算。所以2*(3-1)就等于4了,(1+1)**(5-2)就是2的立方,等于8。使用括號也有助于讓你的表達式讀起來更好理解,比如(minute * 100) / 60,這個也不影響計算結果,不過看起來易于理解。
* Exponentiation has the next highest precedence, so 1 + 2\*\*3 is 9, not 27, and 2 \* 3\*\*2 is 18, not 36.
> 除了括號,所有運算符中,乘方最優先,所以1 + 2\*\*3的結果是9而不是27,2\*3\*\*2結果是18,而不是36。
* Multiplication and Division have higher precedence than Addition andSubtraction. So 2\*3-1 is 5, not 4, and 6+4/2 is 8, not 5.
> 乘除運算比加減優先,譯者認為大家都知道了,這個我就不細說了。
* Operators with the same precedence are evaluated from left to right (except exponentiation). So in the expression degrees / 2 \* pi, the division happens first and the result is multiplied by pi. To divide by 2 π, you can use parentheses or write degrees / 2 / pi.
> 同類運算符從左往右來進行,乘方除外。這個也不細說了,很簡單。
I don’t work very hard to remember the precedence of operators. If I can’t tell by looking at the expression, I use parentheses to make it obvious.
> 我不會花很大力氣來記憶這些運算符的優先級。如果我記不起來,就用括號來讓優先級明確一些就好了。
## 2.6 String operations 字符串操作
In general, you can’t perform mathematical operations on strings, even if the strings look like numbers, so the following are illegal:
> 一般情況下,咱們不能對字符串進行數學運算的,即使字符串看上去像是數字也不行,所以以下這些都是非法操作:
```Python
'2'-'1' 'eggs'/'easy' 'third'*'a charm'
```
But there are two exceptions, + and *.
> 不過+和*可以用在字符串上面。
The + operator performs string concatenation, which means it joins the strings by linking them end-to-end. For example:
> +加號的意思就是字符串拼接了,會把兩個字符串拼到一起,如下所示:
```Python
>>> first = 'throat'
>>> first = 'throat'
>>> second = 'warbler'
>>> second = 'warbler'
>>> first + second
>>> first + second
throatwarbler
```
The * operator also works on strings; it performs repetition. For example,'Spam'*3 is 'SpamSpamSpam'. If one of the values is a string, the other has to be an integer.
> *星號也就是乘法運算符也可以用在字符串上面,效果就是重復。比如'Spam'*3 結果就是
'SpamSpamSpam',重復了三次。需要注意的是字符串必須用整數去乘。
This use of + and * makes sense by analogy with addition and multiplication. Just as 4*3 is equivalent to 4+4+4, we expect 'Spam'*3 to be the same as'Spam'+'Spam'+'Spam', and it is. On the other hand, there is a significant way in which string concatenation and repetition are different from integer addition and multiplication. Can you think of a property that addition has that string concatenation does not?
> 這種加法和乘法實際上就是拼接和重復的意思。就像4*3等同于4+4+4一樣,'Spam'*3 也就等于'Spam'+’Spam’+’Spam'。另外一方面,字符串的拼接重復與整數的加法乘法也有顯著區別。你能想到加法具有些特性是字符拼接所不具有的么?
## 2.7 Comments 注釋
As programs get bigger and more complicated, they get more difficult to read. Formal languages are dense, and it is often difficult to look at a piece of code and figure out what it is doing, or why.
> 程序會越來越龐大,也越復雜了,讀起來就會更難了。公式語言很密集,靠閱讀來理解代碼,總是很困難的。
For this reason, it is a good idea to add notes to your programs to explain in natural language what the program is doing. These notes are called comments, and they start with the # symbol:
> 為了解決閱讀的困難,咱們就可以添加一些筆記到代碼中,把程序的功能用自然語言來解釋一下。這種筆記就叫注釋了,使用井號#來開頭的:
```Python
# compute the percentage of the hour that has elapsed percentage = (minute * 100) / 60
```
In this case, the comment appears on a line by itself. You can also put comments at the end of a line:
> 注釋可以另起一行,也可以放到行末尾:
```Python
percentage = (minute * 100) / 60 # percentage of an hour
```
Everything from the # to the end of the line is ignored—it has no effect on the execution of the program
> 井號#后面的內容都會被忽略,因此不會影響程序的運行結果。
Comments are most useful when they document non-obvious features of the code. It is reasonable to assume that the reader can figure out what the code does; it is more useful to explain why.
> 一般注釋都是用來解釋代碼的一些不明顯的特性。一般情況下讀代碼的人應該能理解代碼的功能是什么,所以用注釋多是要解釋這樣做的目的是什么。
This comment is redundant with the code and useless:
> 這個注釋就顯然是多余的,根本沒必要:
```Python
v = 5 # assign 5 to v
```
This comment contains useful information that is not in the code:
> 這種注釋包含了重要信息,就很重要了:
```python
v = 5 # velocity in meters/second.
```
Good variable names can reduce the need for comments, but long names can make complex expressions hard to read, so there is a tradeoff.
> 變量命名得當的話,就沒必要用太多注釋了,不過名字要是太長了,表達式讀起來也挺麻煩,所以就得權衡著來了。
## 2.8 Debugging 調試
Three kinds of errors can occur in a program: syntax errors, runtime errors, and semantic errors. It is useful to distinguish between them in order to track them down more quickly.
> 程序一般會有三種錯誤:語法錯誤,運行錯誤和語義錯誤。區分這三種錯誤有助于更快速地追蹤錯誤。
* Syntax error:
“Syntax” refers to the structure of a program and the rules about that structure. For example, parentheses have to come in matching pairs, so(1 + 2) is legal, but 8) is a syntax error.
If there is a syntax error anywhere in your program, Python displays an error message and quits, and you will not be able to run the program. During the first few weeks of your programming career, you might spend a lot of time tracking down syntax errors. As you gain experience, you will make fewer errors and find them faster.
> 語法錯誤Syntax error:
語法是指程序的結構和規則。比如括號要成對用。如果你的程序有某個地方出現了語法錯誤,Python會顯示出錯信息并退出,程序就不能運行了。最開始學習編程的這段時間,你遇到的最常見的估計就是這種情況。等你經驗多了,基本就犯的少了,而且也很容易發現了。
* Runtime error:
The second type of error is a runtime error, so called because the error does not appear until after the program has started running. These errors are also called exceptions because they usually indicate that something exceptional (and bad) has happened.
Runtime errors are rare in the simple programs you will see in the first few chapters, so it might be a while before you encounter one.
> 運行錯誤Runtime error:
第二種錯誤就是運行錯誤,顯而易見了,就是直到運行的時候才會出現的錯誤。這種錯誤也被叫做異常,因為一般表示一些意外的尤其是比較糟糕的情況發生了。
* Semantic error:
The third type of error is “semantic”, which means related to meaning. If there is a semantic error in your program, it will run without generating error messages, but it will not do the right thing. It will do something else. Specifically, it will do what you told it to do.
Identifying semantic errors can be tricky because it requires you to work backward by looking at the output of the program and trying to figure out what it is doing.
> 語義錯誤Semantic error:
第三種就是語義錯誤,顧名思義,是跟意義相關。這種錯誤是指你的程序運行沒問題,也不產生錯誤信息,但不能正確工作。程序可能做一些和設計目的不同的事情。發現語義錯誤特別不容易,需要你仔細回顧代碼和程序輸出,要搞清楚到底程序做了什么。
## 2.9 Glossary 術語列表
variable:
A name that refers to a value.
變量:有值的量。
> assignment:
A statement that assigns a value to a variable.
> 賦值:給一個變量賦予值。
state diagram:
A graphical representation of a set of variables and the values they refer to.
> 狀態圖:圖形化表征每個變量的值。
keyword:
A reserved word that is used to parse a program; you cannot use keywords like if, def, and while as variable names.
> 關鍵詞:系統保留的用于解析程序的詞,不能用關鍵詞當做變量名。
operand:
One of the values on which an operator operates.
> 運算數:運算符來進行運算操作的數值。
expression:
A combination of variables, operators, and values that represents a single result.
> 表達式:一組變量、運算數的組合,會產生單值作為結果。
evaluate:
To simplify an expression by performing the operations in order to yield a single value.
> 求解:把表達式所表示的運算計算出來,得到一個單獨的值。
statement:
A section of code that represents a command or action. So far, the statements we have seen are assignments and print statements.
> 聲明:一組表示一種命令或者動作的代碼,目前我們了解的只有賦值語句和打印語句。
execute:
To run a statement and do what it says.
> 運行:將一條語句進行運行。
interactive mode:
A way of using the Python interpreter by typing code at the prompt.
> 交互模式:在提示符后輸入代碼,讓解釋器來運行代碼的模式。
script mode:
A way of using the Python interpreter to read code from a script and run it.
> 腳本模式:將代碼保存成腳本文件,用解釋器運行的模式。
script:
A program stored in a file.
> 腳本:程序以文本形式存成的文件。
order of operations:
Rules governing the order in which expressions involving multiple operators and operands are evaluated.
> 運算符優先級:不同運算符和運算數進行計算的優先順序。
concatenate:
To join two operands end-to-end.
> 拼接:把兩個運算對象相互連接到一起。
comment:
Information in a program that is meant for other programmers (or anyone reading the source code) and has no effect on the execution of the program.
> 注釋:程序中用來解釋代碼含義和運行效果的備注信息,通常給閱讀代碼的人準備的。
syntax error:
An error in a program that makes it impossible to parse (and therefore impossible to interpret).
> 語法錯誤:程序語法上的錯誤,導致程序不能被解釋器解譯,就不能運行了。
exception:
An error that is detected while the program is running.
> 異常:程序運行的時候被探測到的錯誤。
semantics:
The meaning of a program.
> 語義:程序的意義。
semantic error:
An error in a program that makes it do something other than what the programmer intended.
> 語義錯誤:程序運行的結果和料想的不一樣,沒有完成設計的功能,而是干了點其他的事情。
## 2.10 Exercises 練習
### Exercise 1 練習1
Repeating my advice from the previous chapter, whenever you learn a new feature, you should try it out in interactive mode and make errors on purpose to see what goes wrong.
> 像上一章一樣,按我建議的,不論學了什么新內容,你都試著在交互模式上故意犯點錯誤,看看會怎么樣。
* We’ve seen that n = 42 is legal. What about 42 = n?
> 我們都看到了n=42是可以的,那42=n怎么樣?
* How about x = y = 1?
> 再試試x=y=1呢?
* In some languages every statement ends with a semi-colon, ;. What happens if you put a semi-colon at the end of a Python statement?
> 有的語言每個語句結尾都必須有個單引號或者分號,試試在Python句末放個會咋樣?
* What if you put a period at the end of a statement?
> 句尾放個句號試試呢?
* In math notation you can multiply x and y like this: x y. What happens if you try that in Python?
> 數學上你可以把x和y相乘寫成xy,Python里面你這么試試看?
### Exercise 2
Practice using the Python interpreter as a calculator:
1. The volume of a sphere with radius r is 4/3 π r3. What is the volume of a sphere with radius 5?
2. Suppose the cover price of a book is $24.95, but bookstores get a 40% discount. Shipping costs $3 for the first copy and 75 cents for each additional copy. What is the total wholesale cost for 60 copies?
3. If I leave my house at 6:52 am and run 1 mile at an easy pace (8:15 per mile), then 3 miles at tempo (7:12 per mile) and 1 mile at easy pace again, what time do I get home for breakfast?
> 把Python解釋器當做計算器來做下面的練習:
1. 球體體積是三分之四倍的圓周率乘以半徑立方,求半徑為5的球體體積。
2. 加入一本書的封面標價是24.95美元,書店打六折。第一本運費花費3美元,后續每增加一本的運費是75美分。問買60本一共得花多少錢呢?
3. 我早上六點五十二分出門離家,以8:15的節奏跑了一英里,又以7:12的節奏跑了三英里,然后又是8:15的節奏跑一英里,回到家吃飯是幾點?
- 介紹
- 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 額外補充