← 学习库 Think Python (2e) · 中英对照 目录

Chapter 2  Variables, expressions and statements 第 2 章 变量、表达式与语句

本页译自 Think Python 2e(Allen B. Downey)· Chapter 2 Variables, expressions and statements。代码块保留英文原文不翻译;正文段段对照,中文块可用右下角按钮隐藏。

2.1 Values and types 2.1 值与类型

A value is one of the basic things a program works with, like a letter or a number. The values we have seen so far are 1, 1, and 100000006.

「值」是程序处理的基对象之一,比如字母或数字。到目前为止我们看到的值有 11100000009。

These values belong to different types: 1 is an integer, and 100000011 is a string, so-called because it contains a “string” of letters. You (and the interpreter) can identify strings because they are enclosed in quotation marks.

这些值分属不同的「类型」:1 是整数,100000013 是「字符串」,之所以这么叫,是因为它包含一串字母。你和解释器都能认出字符串,因为它们被包在引号里。

If you are not sure what type a value has, the interpreter can tell you.

如果拿不准某个值是什么类型,解释器可以告诉你。
100000014

Not surprisingly, strings belong to the type 100 and integers belong to the type 100. Less obviously, numbers with a decimal point belong to a type called 10000, because these numbers are represented in a format called floating-point.

毫不意外,字符串属于 100 类型,整数属于 100 类型。不太显眼的是,带小数点的数属于 10000 类型,因为它们以「浮点」格式表示。
100000021

What about values like 1000 and 10000? They look like numbers, but they are in quotation marks like strings.

那像 1000 和 10000 这样的值呢?它们看着像数字,却和字符串一样被包在引号里。
100000026

They’re strings.

它们是字符串。

When you type a large integer, you might be tempted to use commas between groups of three digits, as in 100000027. This is not a legal integer in Python, but it is legal:

输入一个很大的整数时,你可能想每三位用逗号分隔,比如 100000028。这在 Python 里并不是合法的整数,但它是合法的:
100000029

Well, that’s not what we expected at all! Python interprets 100000030 as a comma-separated sequence of integers. This is the first example we have seen of a semantic error: the code runs without producing an error message, but it doesn’t do the “right” thing.

哎,这完全不是我们想要的!Python 把 100000031 解释成了一个以逗号分隔的整数序列。这是我们看到的第一例「语义错误」:代码能运行、不报错,却没有做「对」的事。

2.2 Variables 2.2 变量

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.

编程语言最强大的特性之一,就是能操纵「变量」。变量是一个引用了某个值的名字。

An assignment statement creates new variables and gives them values:

「赋值语句」会创建新变量并给它们赋值:
100000032

This example makes three assignments. The first assigns a string to a new variable named 1000000; the second gives the integer 10 to 1; the third assigns the (approximate) value of π to 10.

这个例子做了三次赋值。第一次把一个字符串赋给新变量 1000000;第二次把整数 10 赋给 1;第三次把 π 的(近似)值赋给 10。

A common way to represent variables on paper is to write the name with an arrow pointing to the variable’s 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.

在纸上表示变量,常见的做法是写出名字,再画个箭头指向它的值。这种图叫做「状态图」,因为它展示了每个变量所处的状态(不妨把它想成变量的「心境」)。图 2.1 展示了上面那个例子的结果。

Figure 2.1: State diagram.

图 2.1:状态图(原书插图未收录)

The type of a variable is the type of the value it refers to.

变量的类型,就是它所引用的值的类型。
100000041

2.3 Variable names and keywords 2.3 变量名与关键字

Programmers generally choose names for their variables that are meaningful—they document what the variable is used for.

程序员通常会给变量起一个有意义的名字——用来说明这个变量是做什么的。

Variable names can be arbitrarily long. They can contain both letters and numbers, but they have to begin with a letter. It is legal to use uppercase letters, but it is a good idea to begin variable names with a lowercase letter (you’ll see why later).

变量名可以任意长。它可以同时包含字母和数字,但必须以字母开头。使用大写字母是合法的,但最好以小写字母开头(原因以后你会明白)。

The underscore character, 1, can appear in a name. It is often used in names with multiple words, such as 1000000 or 100000044.

下划线字符 1 可以出现在名字里,常用于由多个单词组成的名字,比如 1000000 或 100000047。

If you give a variable an illegal name, you get a syntax error:

如果给变量起了一个不合法的名字,你会得到一个语法错误:
100000048

100000049 is illegal because it does not begin with a letter. 10000 is illegal because it contains an illegal character, 1. But what’s wrong with 10000?

100000053 不合法,因为它不以字母开头。10000 不合法,因为它含有非法字符 1。但 10000 哪里不对呢?

It turns out that 10000 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.

原来 10000 是 Python 的「关键字」之一。解释器用关键字来识别程序结构,所以不能把它们当变量名用。

Python 2 has 31 keywords:

Python 2 有 31 个关键字:
100000059

In Python 3, 1000 is no longer a keyword, but 10000006 is.

在 Python 3 里,1000 不再是关键字,但 10000006 是。

You might want to keep this list handy. If the interpreter complains about one of your variable names and you don’t know why, see if it is on this list.

你最好把这个列表放在手边。如果解释器抱怨你的某个变量名、你却不明所以,看看它在不在这个列表里。

2.4 Operators and operands 2.4 运算符与操作数

Operators are special symbols that represent computations like addition and multiplication. The values the operator is applied to are called operands.

「运算符」是表示加法、乘法这类运算的特殊符号。运算符所作用的值叫做「操作数」。

The operators 1, 1, 1, 1 and 10 perform addition, subtraction, multiplication, division and exponentiation, as in the following examples:

运算符 111110 分别执行加、减、乘、除和乘方,如下例所示:
100000074

In some other languages, 1 is used for exponentiation, but in Python it is a bitwise operator called XOR. I won’t cover bitwise operators in this book, but you can read about them at 100000076.

在另一些语言里,1 用来表示乘方;但在 Python 里它是一个叫 XOR 的位运算符。本书不会讲位运算符,不过你可以在 100000078 读到相关内容。

In Python 2, the division operator might not do what you expect:

在 Python 2 里,除法运算符可能不按你的预期行事:
100000079

The value of 100000 is 59, and in conventional arithmetic 59 divided by 60 is 0.98333, not 0. The reason for the discrepancy is that Python is performing floor division. When both of the operands are integers, the result is also an integer; floor division chops off the fraction part, so in this example it rounds down to zero.

100000 的值是 59,按常规算术,59 除以 60 等于 0.98333,不是 0。出现这种偏差,是因为 Python 在做「整除(floor division)」。当两个操作数都是整数时,结果也是整数;整除会砍掉小数部分,所以这个例子里它向下取整到零。

In Python 3, the result of this division is a 10000. The new operator 10 performs floor division.

在 Python 3 里,这种除法的结果是一个 10000。新运算符 10 执行整除。

If either of the operands is a floating-point number, Python performs floating-point division, and the result is a 10000:

只要有一个操作数是浮点数,Python 就执行浮点除法,结果也是 10000:
100000088

2.5 Expressions and statements 2.5 表达式与语句

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 (assuming that the variable 1 has been assigned a value):

「表达式」是值、变量和运算符的组合。单独一个值算作表达式,单独一个变量也是,所以下面这些都是合法表达式(假设变量 1 已被赋值):
100000091

A statement is a unit of code that the Python interpreter can execute. We have seen two kinds of statement: print and assignment.

「语句」是 Python 解释器可以执行的一段代码。我们见过两种语句:打印和赋值。

Technically an expression is also a statement, but it is probably simpler to think of them as different things. The important difference is that an expression has a value; a statement does not.

严格说表达式也是一种语句,但把它们看成不同的东西可能更简单。关键区别在于:表达式有值,而语句没有。

2.6 Interactive mode and script mode 2.6 交互模式与脚本模式

One of the benefits of working with an interpreted language is that 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.

用解释型语言的一大好处,是你可以先在交互模式里试一小段代码,再塞进脚本。但交互模式和脚本模式之间有些差别,容易让人犯迷糊。

For example, if you are using Python as a calculator, you might type

比如,当你把 Python 当计算器用时,可能会输入
100000092

The first line assigns a value to 10000, but it has no visible effect. The second line is an expression, so the interpreter evaluates it and displays the result. So we learn that a marathon is about 42 kilometers.

第一行给 10000 赋了值,但没有可见的效果。第二行是个表达式,所以解释器求值并显示结果。于是我们知道一场马拉松大约是 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 其实求了值,但除非你让它显示,否则它不会打印这个值:
100000095

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

例如,下面这个脚本
100000096

produces the output

产生的输出是
100000097

The assignment statement produces no output.

赋值语句不产生输出。

Exercise 1

习题 1

Type the following statements in the Python interpreter to see what they do:

在 Python 解释器里输入下面这些语句,看看它们各自做什么:
100000098

Now put the same statements into 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.

现在把这些语句放进一个脚本并运行。输出是什么?把脚本改一改,把每个表达式都变成 print 语句,再运行一次。

2.7 Order of operations 2.7 求值顺序

When more than one operator appears in an expression, the order of evaluation depends on the rules of precedence. For mathematical operators, Python follows mathematical convention. The acronym PEMDAS is a useful way to remember the rules:

当表达式里出现多个运算符时,求值顺序取决于「优先级规则」。对数学运算符,Python 遵循数学惯例。助记词 PEMDAS 能帮你记住这些规则:

I don’t work very hard to remember rules of precedence for other operators. If I can’t tell by looking at the expression, I use parentheses to make it obvious.

对于其他运算符的优先级规则,我懒得花力气去记。如果看一眼表达式看不出来,我就加括号让它一目了然。

2.8 String operations 2.8 字符串操作

In general, you can’t perform mathematical operations on strings, even if the strings look like numbers, so the following are illegal:

一般来说,不能对字符串做数学运算,哪怕字符串看着像数字——所以下面这些都是非法的:
100000119

The 1 operator works with strings, but it might not do what you expect: it performs concatenation, which means joining the strings by linking them end-to-end. For example:

1 运算符对字符串也有效,但可能不按你的预期:它做的是「拼接」,也就是把字符串首尾相连拼起来。例如:
100000122

The output of this program is 100000123.

这段程序的输出是 100000124。

The 1 operator also works on strings; it performs repetition. For example, 10000012 is 100000127. If one of the operands is a string, the other has to be an integer.

1 运算符对字符串也有效;它做的是重复。例如 10000012 等于 100000130。如果其中一个操作数是字符串,另一个必须是整数。

This use of 1 and 1 makes sense by analogy with addition and multiplication. Just as 100 is equivalent to 10000, we expect 10000013 to be the same as 100000136, 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?

11 来做拼接和重复,类比加法与乘法说得通。正如 100 等价于 10000,我们预期 10000014 等于 100000142,事实也的确如此。话虽如此,字符串拼接、重复跟整数加法、乘法有一处重要不同。你能想出一种加法具备、而字符串拼接不具备的性质吗?

2.9 Comments 2.9 注释

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 1 symbol:

因此,给程序加注释、用自然语言说明它在做什么,是个好习惯。这些注释叫做「注释」,以 1 符号开头:
100000145

In this case, the comment appears on a line by itself. You can also put comments at the end of a line:

这里注释独占一行。你也可以把注释放在行尾:
100000146

Everything from the 1 to the end of the line is ignored—it has no effect on the program.

1 到行尾的内容都会被忽略——它对程序没有任何影响。

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 much more useful to explain why.

注释在说明代码里不明显的地方时最有价值。读者能看懂代码做什么是合理的;解释为什么要有用得多。

This comment is redundant with the code and useless:

这条注释跟代码重复,毫无用处:
100000149

This comment contains useful information that is not in the code:

这条注释包含代码里没有的有用信息:
100000150

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.10 Debugging 2.10 调试

At this point the syntax error you are most likely to make is an illegal variable name, like 10000 and 10000, which are keywords, or 1000001 and 1000001, which contain illegal characters.

现阶段你最可能犯的语法错误,是用了非法的变量名,比如 10000、10000(它们是关键字),或者 1000001、1000001(含有非法字符)。

If you put a space in a variable name, Python thinks it is two operands without an operator:

如果在变量名里加了空格,Python 会把它当成两个没有运算符的操作数:
100000159

For syntax errors, the error messages don’t help much. The most common messages are 100000160 and 100000161, neither of which is very informative.

对于语法错误,错误信息帮不上多大忙。最常见的两条是 100000162 和 100000163,都不怎么说明问题。

The runtime error you are most likely to make is a “use before def;” that is, trying to use a variable before you have assigned a value. This can happen if you spell a variable name wrong:

你最可能犯的运行时错误是「定义前先用」——也就是在给变量赋值之前就试图使用它。变量名拼错时就会发生:
100000164

Variables names are case sensitive, so 10000 is not the same as 10000.

变量名区分大小写,所以 10000 和 10000 不是同一个名字。

At this point the most likely cause of a semantic error is the order of operations. For example, to evaluate 1/2 π, you might be tempted to write

现阶段最可能的语义错误成因是运算优先级。比如,要求 1/2 π,你可能会随手写成
100000169

But the division happens first, so you would get π / 2, which is not the same thing! There is no way for Python to know what you meant to write, so in this case you don’t get an error message; you just get the wrong answer.

但除法先执行,于是你得到的是 π/2,根本不是一回事!Python 无从知道你想写什么,所以这种情况不会报错,你只会得到一个错误的答案。

2.11 Glossary 2.11 术语表

value:
One of the basic units of data, like a number or string, that a program manipulates.
type:
A category of values. The types we have seen so far are integers (type 100), floating-point numbers (type 10000), and strings (type 100).
integer:
A type that represents whole numbers.
floating-point:
A type that represents numbers with fractional parts.
string:
A type that represents sequences of characters.
variable:
A name that refers to a value.
statement:
A section of code that represents a command or action. So far, the statements we have seen are assignments and print statements.
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 by the compiler to parse a program; you cannot use keywords like 10, 100, and 10000 as variable names.
operator:
A special symbol that represents a simple computation like addition, multiplication, or string concatenation.
operand:
One of the values on which an operator operates.
floor division:
The operation that divides two numbers and chops off the fraction part.
expression:
A combination of variables, operators, and values that represents a single result value.
evaluate:
To simplify an expression by performing the operations in order to yield a single value.
rules of precedence:
The set of 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.
value 值:
程序所操纵的基本数据单元之一,比如数字或字符串。
type 类型:
值的一个类别。到目前为止我们见过的类型有整数(100 类型)、浮点数(10000 类型)和字符串(100 类型)。
integer 整数:
表示整数的类型。
floating-point 浮点:
表示带小数部分的数的类型。
string 字符串:
表示字符序列的类型。
variable 变量:
引用某个值的名字。
statement 语句:
代表一条命令或动作的一段代码。到目前为止我们见过的语句有赋值语句和打印语句。
assignment 赋值:
把值赋给一个变量的语句。
state diagram 状态图:
一组变量及其所引用的值的图形表示。
keyword 关键字:
被编译器用来解析程序的保留字;你不能用 10、100、10000 这样的关键字作变量名。
operator 运算符:
表示简单运算(如加法、乘法或字符串拼接)的特殊符号。
operand 操作数:
运算符所作用的一个值。
floor division 整除:
把两个数相除并砍掉小数部分的操作。
expression 表达式:
变量、运算符和值的组合,代表一个单一的结果值。
evaluate 求值:
按运算顺序执行运算,化简表达式以得到一个单一的值。
rules of precedence 优先级规则:
规定包含多个运算符和操作数的表达式按什么顺序求值的规则集合。
concatenate 拼接:
把两个操作数首尾相连地接起来。
comment 注释:
程序里写给其他程序员(或任何阅读源代码的人)看的信息,对程序的执行没有影响。

2.12 Exercises 2.12 习题

Exercise 2

习题 2

Assume that we execute the following assignment statements:

假设我们执行了以下赋值语句:
100000182

For each of the following expressions, write the value of the expression and the type (of the value of the expression).

对于下面每个表达式,写出它的值和类型(即该表达式的值的类型)。
  1. 1000001
  2. 100000184
  3. 10000018
  4. 100000186
  5. 100000187
  1. 1000001
  2. 100000189
  3. 10000019
  4. 100000191
  5. 100000192

Use the Python interpreter to check your answers.

用 Python 解释器核对你的答案。

Exercise 3

习题 3

Practice using the Python interpreter as a calculator:

练习把 Python 解释器当计算器用:
  1. The volume of a sphere with radius r is 4/3 π r3. What is the volume of a sphere with radius 5? Hint: 392.7 is wrong!
  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?
  1. 半径为 r 的球体积是 4/3 π r3。半径为 5 的球体积是多少?提示:392.7 是错的!
  2. 假设一本书的标价是 \$24.95,但书店能拿到 40% 的折扣。运费为首本 \$3,此后每本 75 美分。60 本的批发总价是多少?
  3. 如果我早上 6:52 出门,先以轻松配速跑 1 英里(每英里 8:15),再以节奏配速跑 3 英里(每英里 7:12),最后以轻松配速再跑 1 英里,我几点到家吃早饭?