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 .
1、1 和 100000009 。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.
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.
Figure 2.1: State diagram.
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:
100000059
In Python 3, 1000 is no longer a keyword, but 10000006 is.
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:
1、1、1、1 和 10 分别执行加、减、乘、除和乘方,如下例所示: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:
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.
10000。新运算符 10 执行整除。If either of the operands is a floating-point number, Python performs floating-point division, and the result is a 10000:
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.
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
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:
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
Type the following statements in the Python interpreter to see what they do:
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.
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:
- 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,
100000099 is 4, and100000100 is 8. You can also use parentheses to make an expression easier to read, as in100000101 , even if it doesn’t change the result. - Exponentiation has the next highest precedence, so
100000 is 3, not 4, and100000 is 3, not 27. - Multiplication and Division have the same precedence, which is higher than Addition and Subtraction, which also have the same precedence. So
10000 is 5, not 4, and10000 is 8, not 5. - Operators with the same precedence are evaluated from left to right (except exponentiation). So in the expression
100000106 , the division happens first and the result is multiplied by10. To divide by 2 π, you can use parentheses or write100000108 .
- P(括号)优先级最高,可强制表达式按你想要的顺序求值。由于括号内的表达式先算,
100000109 等于 4,100000110 等于 8。即使不改变结果,你也可以用括号让表达式更易读,比如100000111 。 - E(乘方)优先级次之,所以
100000 是 3 而不是 4,100000 是 3 而不是 27。 - M(乘)和 D(除)优先级相同,且高于 A(加)和 S(减),后两者优先级也相同。所以
10000 是 5 而不是 4,10000 是 8 而不是 5。 - 优先级相同的运算符从左到右依次求值(乘方除外)。所以在表达式
100000116 里,先算除法,再把结果乘以10。要除以 2π,可以用括号,或者写成100000118 。
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?
1 和 1 来做拼接和重复,类比加法与乘法说得通。正如 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:
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
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.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 (type10000), and strings (type100). - 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, and10000 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
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).
100000110000018410000018100000186100000187
100000110000018910000019100000191100000192
Use the Python interpreter to check your answers.
Exercise 3
Practice using the Python interpreter as a calculator:
- 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!
- 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?
- 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?
- 半径为 r 的球体积是 4/3 π r3。半径为 5 的球体积是多少?提示:392.7 是错的!
- 假设一本书的标价是 \$24.95,但书店能拿到 40% 的折扣。运费为首本 \$3,此后每本 75 美分。60 本的批发总价是多少?
- 如果我早上 6:52 出门,先以轻松配速跑 1 英里(每英里 8:15),再以节奏配速跑 3 英里(每英里 7:12),最后以轻松配速再跑 1 英里,我几点到家吃早饭?