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

Chapter 1  The way of the program 第 1 章 编程之道

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

The goal of this book is to teach you to think like a computer scientist. This way of thinking combines some of the best features of mathematics, engineering, and natural science. Like mathematicians, computer scientists use formal languages to denote ideas (specifically computations). Like engineers, they design things, assembling components into systems and evaluating tradeoffs among alternatives. Like scientists, they observe the behavior of complex systems, form hypotheses, and test predictions.

本书的目标是教你像计算机科学家那样思考。这种思维方式融合了数学、工程学和自然科学的一些最优特性。像数学家一样,计算机科学家使用形式语言来表述思想(特别是计算过程)。像工程师一样,他们设计事物,将组件装配成系统,并权衡各种替代方案。像科学家一样,他们观察复杂系统的行为、形成假设并检验预测。

The single most important skill for a computer scientist is problem solving. Problem solving means the ability to formulate problems, think creatively about solutions, and express a solution clearly and accurately. As it turns out, the process of learning to program is an excellent opportunity to practice problem-solving skills. That’s why this chapter is called, “The way of the program.”

计算机科学家最重要的一项技能就是解决问题。解决问题意味着有能力把问题表述清楚、创造性地思考解法,并清晰准确地表达出解决方案。事实证明,学习编程的过程正是锻炼解决问题能力的绝佳机会。这也正是本章名为「编程之道」的原因。

On one level, you will be learning to program, a useful skill by itself. On another level, you will use programming as a means to an end. As we go along, that end will become clearer.

从一层意义上说,你将学习编程,这本身就是一项有用的技能。从另一层意义上说,你将把编程当作达成某种目的的手段。随着我们逐步推进,那个目的会变得越来越清晰。

1.1 The Python programming language 1.1 Python 编程语言

The programming language you will learn is Python. Python is an example of a high-level language; other high-level languages you might have heard of are C, C++, Perl, and Java.

你将学习的编程语言是 Python。Python 是高级语言的一个例子;你可能听过的其他高级语言还有 C、C++、Perl 和 Java。

There are also low-level languages, sometimes referred to as “machine languages” or “assembly languages.” Loosely speaking, computers can only run programs written in low-level languages. So programs written in a high-level language have to be processed before they can run. This extra processing takes some time, which is a small disadvantage of high-level languages.

也有低级语言,有时被称为「机器语言」或「汇编语言」。粗略地说,计算机只能运行用低级语言编写的程序。所以用高级语言写的程序必须先经过处理才能运行。这份额外的处理要花一点时间,这是高级语言的一个小缺点。

The advantages are enormous. First, it is much easier to program in a high-level language. Programs written in a high-level language take less time to write, they are shorter and easier to read, and they are more likely to be correct. Second, high-level languages are portable, meaning that they can run on different kinds of computers with few or no modifications. Low-level programs can run on only one kind of computer and have to be rewritten to run on another.

高级语言的优势是巨大的。首先,用高级语言编程要容易得多:程序写得更快、更短、更易读,也更可能正确。其次,高级语言具有可移植性,意思是它们只需极少修改甚至不修改,就能在不同种类的计算机上运行。而低级程序只能在某一种计算机上运行,要换一种机器就得重写。

Due to these advantages, almost all programs are written in high-level languages. Low-level languages are used only for a few specialized applications.

出于这些优势,几乎所有程序都用高级语言编写。低级语言只用于少数专用场合。

Two kinds of programs process high-level languages into low-level languages: interpreters and compilers. An interpreter reads a high-level program and executes it, meaning that it does what the program says. It processes the program a little at a time, alternately reading lines and performing computations. Figure 1.1 shows the structure of an interpreter.

把高级语言处理成低级语言的有两类程序:解释器编译器。解释器读取一个高级语言程序并执行它,也就是按程序说的去做。它每次处理一小部分程序,交替地读取代码行并执行计算。图 1.1 展示了一种解释器的结构。

Figure 1.1: An interpreter processes the program a little at a time, alternately reading lines and performing computations.

图 1.1:解释器每次处理程序的一小部分,交替地读取代码行并执行计算。(原书插图未收录)

A compiler reads the program and translates it completely before the program starts running. In this context, the high-level program is called the source code, and the translated program is called the object code or the executable. Once a program is compiled, you can execute it repeatedly without further translation. Figure 1.2 shows the structure of a compiler.

编译器读取程序,并在程序开始运行之前把它完整地翻译出来。在这里,那个高级语言程序被称为源代码,翻译后的程序被称为目标代码可执行文件。程序一旦编译完成,就可以反复执行,无需再翻译。图 1.2 展示了编译器的结构。

Figure 1.2: A compiler translates source code into object code, which is run by a hardware executor.

图 1.2:编译器将源代码翻译为目标代码,由硬件执行器运行。(原书插图未收录)

Python is considered an interpreted language because Python programs are executed by an interpreter. There are two ways to use the interpreter: interactive mode and script mode. In interactive mode, you type Python programs and the interpreter displays the result:

Python 被认为是一种解释型语言,因为 Python 程序是由解释器执行的。使用解释器有两种方式:交互模式脚本模式。在交互模式下,你键入 Python 程序,解释器就显示结果:
>>> 1 + 1
2

The chevron, >>>, is the prompt the interpreter uses to indicate that it is ready. If you type 1 + 1, the interpreter replies 2.

这个 1 + 10008 是解释器用来提示「我已就绪」的提示符。如果你键入 1 + 1,解释器就会回答 2

Alternatively, you can store code in a file and use the interpreter to execute the contents of the file, which is called a script. By convention, Python scripts have names that end with 200.

另一种办法是把代码存进一个文件,再让解释器执行这个文件的内容,这称为脚本。按照惯例,Python 脚本的文件名以 200 结尾。

To execute the script, you have to tell the interpreter the name of the file. If you have a script named 1 + 10013 and you are working in a UNIX command window, you type 1 + 10014. In other development environments, the details of executing scripts are different. You can find instructions for your environment at the Python website 1 + 10015.

要执行脚本,你得告诉解释器文件名。如果你有一个名为 1 + 10016 的脚本,并且工作在 UNIX 命令行窗口里,就键入 1 + 10017。在其他开发环境中,执行脚本的细节各不相同。你可以在 Python 网站 1 + 10018 上找到针对你所在环境的说明。

Working in interactive mode is convenient for testing small pieces of code because you can type and execute them immediately. But for anything more than a few lines, you should save your code as a script so you can modify and execute it in the future.

用交互模式来测试小段代码很方便,因为你可以立刻键入并执行。但凡是超过几行的东西,你都应该把代码存成脚本,以便将来修改和再次执行。

1.2 What is a program? 1.2 什么是程序?

A program is a sequence of instructions that specifies how to perform a computation. The computation might be something mathematical, such as solving a system of equations or finding the roots of a polynomial, but it can also be a symbolic computation, such as searching and replacing text in a document or (strangely enough) compiling a program.

程序是一串指令,规定如何完成一次计算。这个计算可能是数学性的,比如求解方程组或求多项式的根;也可能是符号性的,比如在文档里查找并替换文字,或者(说来奇怪)编译一个程序。

The details look different in different languages, but a few basic instructions appear in just about every language:

不同语言的具体细节各不相同,但有几个基本指令几乎出现在每种语言里:
input:
Get data from the keyboard, a file, or some other device.
output:
Display data on the screen or send data to a file or other device.
math:
Perform basic mathematical operations like addition and multiplication.
conditional execution:
Check for certain conditions and execute the appropriate code.
repetition:
Perform some action repeatedly, usually with some variation.
input 输入:
从键盘、文件或其他设备获取数据。
output 输出:
把数据显示在屏幕上,或发送到文件或其他设备。
math 数学:
执行加法、乘法之类的基本数学运算。
conditional execution 条件执行:
检查某些条件,并执行相应的代码。
repetition 重复:
反复执行某个动作,通常带一些变化。

Believe it or not, that’s pretty much all there is to it. Every program you’ve ever used, no matter how complicated, is made up of instructions that look pretty much like these. So you can think of programming as the process of breaking a large, complex task into smaller and smaller subtasks until the subtasks are simple enough to be performed with one of these basic instructions.

不管你信不信,这基本上就是全部了。你用过的每一个程序,不管多复杂,都是由这些看起来差不多的指令组成的。所以你可以把编程看成这样一个过程:把庞大、复杂的任务不断拆成越来越小的子任务,直到子任务简单到能用上面某条基本指令完成。

That may be a little vague, but we will come back to this topic when we talk about algorithms.

这话可能有点含糊,但等我们讲到算法时还会回到这个话题。

1.3 What is debugging? 1.3 什么是调试?

Programming is error-prone. For whimsical reasons, programming errors are called bugs and the process of tracking them down is called debugging.

编程很容易出错。不知为何,编程错误被叫作缺陷(bug),而追踪这些错误的过程叫作调试

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.

程序里会出现三类错误:语法错误、运行时错误和语义错误。区分它们有助于更快地找到错误。

1.3.1 Syntax errors 1.3.1 语法错误

Python can only execute a program if the syntax is correct; otherwise, the interpreter displays an error message. 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 + 100 is legal, but 20 is a syntax error.

只有当语法正确时,Python 才能执行程序;否则解释器会显示一条错误信息。语法指的是程序的结构以及关于该结构的规则。例如,括号必须成对出现,所以 1 + 100 是合法的,而 20 是一个语法错误

In English, readers can tolerate most syntax errors, which is why we can read the poetry of e. e. cummings without spewing error messages. Python is not so forgiving. If there is a single syntax error anywhere in your program, Python will display an error message and quit, and you will not be able to run your program. During the first few weeks of your programming career, you will probably spend a lot of time tracking down syntax errors. As you gain experience, you will make fewer errors and find them faster.

在英语里,读者能容忍大多数语法错误,所以我们读 e. e. cummings 的诗时不会吐出报错信息。Python 可没这么宽容。只要程序里有哪怕一处语法错误,Python 就会显示错误信息然后退出,你也就没法运行程序。在刚学编程的头几周,你可能要花很多时间去追查语法错误。随着经验增长,你出的错会变少,找错也会变快。

1.3.2 Runtime errors 1.3.2 运行时错误

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.

在你最初几章会看到的那些简单程序里,运行时错误很少见,所以你可能要过一阵子才会撞上一个。

1.3.3 Semantic errors 1.3.3 语义错误

The third type of error is the semantic error. If there is a semantic error in your program, it will run successfully in the sense that the computer will not generate any 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.

第三类错误是语义错误。如果程序里有语义错误,它照样能「成功」运行,计算机不会报任何错误信息,但它做的不是正确的事。它会去做别的事——具体地说,去做你让它做的事。

The problem is that the program you wrote is not the program you wanted to write. The meaning of the program (its semantics) is wrong. 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.

问题在于,你写出来的程序并不是你本来想写的那个程序。这个程序的含义(它的语义)是错的。找出语义错误可能很费劲,因为这要求你倒着推:看着程序的输出,努力弄明白它到底在干什么。

1.3.4 Experimental debugging 1.3.4 实验式调试

One of the most important skills you will acquire is debugging. Although it can be frustrating, debugging is one of the most intellectually rich, challenging, and interesting parts of programming.

你将习得的最重要技能之一便是调试。尽管它令人沮丧,但调试也是编程中最富智识、最具挑战也最有趣的部分之一。

In some ways, debugging is like detective work. You are confronted with clues, and you have to infer the processes and events that led to the results you see.

从某些方面看,调试像侦探工作。你面对一堆线索,必须推断出是哪些过程和事件导致了你看到的结果。

Debugging is also like an experimental science. Once you have an idea about what is going wrong, you modify your program and try again. If your hypothesis was correct, then you can predict the result of the modification, and you take a step closer to a working program. If your hypothesis was wrong, you have to come up with a new one. As Sherlock Holmes pointed out, “When you have eliminated the impossible, whatever remains, however improbable, must be the truth.” (A. Conan Doyle, The Sign of Four)

调试也像一门实验科学。一旦你对哪里出了错有了想法,就修改程序再试一次。如果假设是对的,你就能预测修改的结果,于是离能跑的程序又近了一步。如果假设错了,你就得想出新的假设。正如福尔摩斯所说:「当你排除一切不可能,剩下的无论多么不可思议,都必定是真相。」(阿瑟·柯南·道尔,《四签名》)

For some people, programming and debugging are the same thing. That is, programming is the process of gradually debugging a program until it does what you want. The idea is that you should start with a program that does something and make small modifications, debugging them as you go, so that you always have a working program.

对有些人来说,编程和调试就是同一回事。也就是说,编程就是逐步调试一个程序,直到它做你想要的事。其思路是:你先从一个能做点什么的程序起步,再做小的修改,边改边调,从而始终保有一个能跑的程序。

For example, Linux is an operating system that contains thousands of lines of code, but it started out as a simple program Linus Torvalds used to explore the Intel 80386 chip. According to Larry Greenfield, “One of Linus’s earlier projects was a program that would switch between printing AAAA and BBBB. This later evolved to Linux.” (The Linux Users’ Guide Beta Version 1).

举个例子,Linux 是一个包含成千上万行代码的操作系统,但它起初只是 Linus Torvalds 用来探索 Intel 80386 芯片的一个小程序。据 Larry Greenfield 说:「Linus 早期的其中一个项目,是一个能在打印 AAAA 和 BBBB 之间切换的程序。这后来演变成了 Linux。」(《Linux 用户指南》Beta 版 1)。

Later chapters will make more suggestions about debugging and other programming practices.

后面的章节还会就调试和其他编程实践给出更多建议。

1.4 Formal and natural languages 1.4 形式语言与自然语言

Natural languages are the languages people speak, such as English, Spanish, and French. They were not designed by people (although people try to impose some order on them); they evolved naturally.

自然语言是人们所说的语言,比如英语、西班牙语和法语。它们不是被人设计出来的(尽管人们试图给它们强加一些秩序),而是自然演化出来的。

Formal languages are languages that are designed by people for specific applications. For example, the notation that mathematicians use is a formal language that is particularly good at denoting relationships among numbers and symbols. Chemists use a formal language to represent the chemical structure of molecules. And most importantly:

形式语言是人们为特定应用而设计出来的语言。例如,数学家使用的记号就是一种特别擅长表示数字与符号之间关系的形式语言。化学家使用一种形式语言来表示分子的化学结构。而最重要的是:

Programming languages are formal languages that have been designed to express computations.

编程语言是专门用来表达计算的形式语言。

Formal languages tend to have strict rules about syntax. For example, 3 + 3 = 6 is a syntactically correct mathematical statement, but 3 + = 3 \$ 6 is not. H2O is a syntactically correct chemical formula, but 2Zz is not.

形式语言往往对语法有严格的规则。例如,3 + 3 = 6 是一个语法正确的数学陈述,但 3 + = 3 \$ 6 不是。H2O 是一个语法正确的化学式,但 2Zz 不是。

Syntax rules come in two flavors, pertaining to tokens and structure. Tokens are the basic elements of the language, such as words, numbers, and chemical elements. One of the problems with 3 + = 3 \$ 6 is that \$ is not a legal token in mathematics (at least as far as I know). Similarly, 2Zz is not legal because there is no element with the abbreviation Zz.

语法规则分两类,分别涉及标记和结构。标记是语言的基本元素,比如单词、数字和化学元素。3 + = 3 \$ 6 的问题之一在于,\$ 在数学中并不是一个合法的标记(至少据我所知是这样)。类似地,2Zz 也不合法,因为没有缩写为 Zz 的元素。

The second type of syntax rule pertains to the structure of a statement; that is, the way the tokens are arranged. The statement 3 + = 3 is illegal because even though + and = are legal tokens, you can’t have one right after the other. Similarly, in a chemical formula the subscript comes after the element name, not before.

第二类语法规则涉及语句的结构,也就是标记的排列方式。语句 3 + = 3 是非法的,因为尽管 + 和 = 都是合法标记,你却不能让它们紧挨着。同理,在化学式中,下标要写在元素名之后,而不是之前。

Exercise 1

习题 1

Write a well-structured English sentence with invalid tokens in it. Then write another sentence with all valid tokens but with invalid structure.

写一个结构良好的英文句子,但其中包含不合法的标记。然后再写一个所有标记都合法、但结构不合法的句子。

When you read a sentence in English or a statement in a formal language, you have to figure out what the structure of the sentence is (although in a natural language you do this subconsciously). This process is called parsing.

当你读一句英文或一条形式语言里的语句时,你得弄清这句话的结构是什么(尽管在自然语言里你是下意识地做这件事的)。这个过程叫作解析

For example, when you hear the sentence, “The penny dropped,” you understand that “the penny” is the subject and “dropped” is the predicate. Once you have parsed a sentence, you can figure out what it means, or the semantics of the sentence. Assuming that you know what a penny is and what it means to drop, you will understand the general implication of this sentence.

例如,当你听到「The penny dropped( penny 掉了)」这句话时,你会明白「the penny」是主语,「dropped」是谓语。一旦解析了句子,你就能弄清它的意思,也就是它的语义。假设你知道 penny 是什么、也知道 drop 是什么意思,你就会明白这句话的大致含义。

Although formal and natural languages have many features in common—tokens, structure, syntax, and semantics—there are some differences:

尽管形式语言与自然语言有许多共同点——标记、结构、语法和语义——它们之间仍有一些差异:
ambiguity:
Natural languages are full of ambiguity, which people deal with by using contextual clues and other information. Formal languages are designed to be nearly or completely unambiguous, which means that any statement has exactly one meaning, regardless of context.
redundancy:
In order to make up for ambiguity and reduce misunderstandings, natural languages employ lots of redundancy. As a result, they are often verbose. Formal languages are less redundant and more concise.
literalness:
Natural languages are full of idiom and metaphor. If I say, “The penny dropped,” there is probably no penny and nothing dropping (this idiom means that someone realized something after a period of confusion). Formal languages mean exactly what they say.
ambiguity 歧义性:
自然语言充满歧义,人们靠语境线索和其他信息来应对。形式语言则被设计得近乎或完全无歧义,也就是说,任何一条语句都只有唯一一种含义,与上下文无关。
redundancy 冗余性:
为了弥补歧义、减少误解,自然语言大量使用冗余。结果就是它们往往很啰嗦。形式语言冗余较少,因而更紧凑。
literalness 字面性:
自然语言充满习语和比喻。如果我说「The penny dropped」,很可能既没有 penny,也没有什么东西在掉落(这个习语指的是某人在一阵困惑之后忽然想通了)。形式语言说的就是字面意思。

People who grow up speaking a natural language—everyone—often have a hard time adjusting to formal languages. In some ways, the difference between formal and natural language is like the difference between poetry and prose, but more so:

所有从小讲自然语言长大的人,往往都很难适应形式语言。从某些方面看,形式语言与自然语言之间的差别,有点像诗歌与散文之间的差别,只是更甚:
Poetry:
Words are used for their sounds as well as for their meaning, and the whole poem together creates an effect or emotional response. Ambiguity is not only common but often deliberate.
Prose:
The literal meaning of words is more important, and the structure contributes more meaning. Prose is more amenable to analysis than poetry but still often ambiguous.
Programs:
The meaning of a computer program is unambiguous and literal, and can be understood entirely by analysis of the tokens and structure.
Poetry 诗歌:
词语既取声音也取意义,整首诗共同营造出一种效果或情绪反应。歧义不仅常见,而且常常是刻意为之。
Prose 散文:
词语的字面含义更重要,结构也贡献了更多意义。散文比诗歌更经得起分析,但依然常常有歧义。
Programs 程序:
计算机程序的含义明确且无歧义,完全可以靠分析其标记和结构来彻底理解。

Here are some suggestions for reading programs (and other formal languages). First, remember that formal languages are much more dense than natural languages, so it takes longer to read them. Also, the structure is very important, so it is usually not a good idea to read from top to bottom, left to right. Instead, learn to parse the program in your head, identifying the tokens and interpreting the structure. Finally, the details matter. Small errors in spelling and punctuation, which you can get away with in natural languages, can make a big difference in a formal language.

读程序(以及其他形式语言)时有几条建议。首先,记住形式语言比自然语言密集得多,所以读起来更费时间。其次,结构非常重要,所以通常不要从上到下、从左到右地读。相反,要学会在脑中解析程序,识别标记、理解结构。最后,细节很重要。在自然语言里可以马虎的拼写和标点小错,在形式语言里可能造成天差地别。

1.5 The first program 1.5 第一个程序

Traditionally, the first program you write in a new language is called “Hello, World!” because all it does is display the words “Hello, World!”. In Python, it looks like this:

传统上,你用一门新语言写的第一个程序都叫「Hello, World!」,因为它唯一做的事就是显示「Hello, World!」这几个字。在 Python 里,它长这样:
1 + 10023

This is an example of a print statement, which doesn’t actually print anything on paper. It displays a value on the screen. In this case, the result is the words

这是一个打印语句的例子,它其实不会在纸上打印任何东西,而是在屏幕上显示一个值。在这里,结果就是那几个字
1 + 10024

The quotation marks in the program mark the beginning and end of the text to be displayed; they don’t appear in the result.

程序里的引号标出了要显示的文本的起点和终点;它们本身不会出现在结果里。

In Python 3, the syntax for printing is slightly different:

在 Python 3 里,打印的语法稍有不同:
1 + 10025

The parentheses indicate that 1 + 1 is a function. We’ll get to functions in Chapter 3.

那对括号表明 1 + 1 是一个函数。我们会在第 3 章讲到函数。

For the rest of this book, I’ll use the print statement. If you are using Python 3, you will have to translate. But other than that, there are very few differences we have to worry about.

本书余下的部分,我会用打印语句。如果你用的是 Python 3,就得自己翻译一下。但除此之外,需要我们操心的差别很少。

1.6 Debugging 1.6 调试

It is a good idea to read this book in front of a computer so you can try out the examples as you go. You can run most of the examples in interactive mode, but if you put the code in a script, it is easier to try out variations.

最好坐在电脑前读这本书,这样你可以边读边试例子。大部分例子都能在交互模式下运行,但如果你把代码放进脚本,尝试各种变体就会更容易。

Whenever you are experimenting with a new feature, you should try to make mistakes. For example, in the “Hello, world!” program, what happens if you leave out one of the quotation marks? What if you leave out both? What if you spell 1 + 1 wrong?

每当你在试验一个新特性时,都应该试着搞错。比如,在「Hello, world!」程序里,如果你漏掉一个引号会怎样?两个都漏掉呢?把 1 + 1 拼错呢?

This kind of experiment helps you remember what you read; it also helps with debugging, because you get to know what the error messages mean. It is better to make mistakes now and on purpose than later and accidentally.

这种实验能帮你记住读到的东西;它也有助于调试,因为你会逐渐懂得那些错误信息是什么意思。与其日后不小心犯错,不如现在就故意犯错。

Programming, and especially debugging, sometimes brings out strong emotions. If you are struggling with a difficult bug, you might feel angry, despondent or embarrassed.

编程,尤其是调试,有时会引发强烈的情绪。如果你正被一个难缠的缺陷折磨,你可能会感到愤怒、沮丧或难堪。

There is evidence that people naturally respond to computers as if they were people. When they work well, we think of them as teammates, and when they are obstinate or rude, we respond to them the same way we respond to rude, obstinate people (Reeves and Nass, The Media Equation: How People Treat Computers, Television, and New Media Like Real People and Places).

有证据表明,人们会本能地把计算机当成真人来对待。当它们好用时,我们视其为队友;当它们固执或无礼时,我们的反应就跟对待那些无礼又固执的人一样(Reeves 与 Nass,《媒体等式:人们如何像对待真人和真实地点那样对待计算机、电视和新媒体》)。

Preparing for these reactions might help you deal with them. One approach is to think of the computer as an employee with certain strengths, like speed and precision, and particular weaknesses, like lack of empathy and inability to grasp the big picture.

对这些反应有所准备,或许能帮你应对它们。一种办法是把计算机想象成一名员工,它有某些长处,比如速度和精确;也有特定的短处,比如缺乏共情、把握不了全局。

Your job is to be a good manager: find ways to take advantage of the strengths and mitigate the weaknesses. And find ways to use your emotions to engage with the problem, without letting your reactions interfere with your ability to work effectively.

你的职责是当好经理:想办法发挥它的长处、弥补它的短处。还要找到办法,利用你的情绪去投入问题,又不让这些情绪干扰你有效工作的能力。

Learning to debug can be frustrating, but it is a valuable skill that is useful for many activities beyond programming. At the end of each chapter there is a debugging section, like this one, with my thoughts about debugging. I hope they help!

学调试可能令人沮丧,但它是一项宝贵的技能,在编程之外的许多事情上也用得上。每章末尾都有一个像这样的调试小节,附上我对调试的一些想法。希望它们能帮到你!

1.7 Glossary 1.7 术语表

problem solving:
The process of formulating a problem, finding a solution, and expressing the solution.
high-level language:
A programming language like Python that is designed to be easy for humans to read and write.
low-level language:
A programming language that is designed to be easy for a computer to execute; also called “machine language” or “assembly language.”
portability:
A property of a program that can run on more than one kind of computer.
interpret:
To execute a program in a high-level language by translating it one line at a time.
compile:
To translate a program written in a high-level language into a low-level language all at once, in preparation for later execution.
source code:
A program in a high-level language before being compiled.
object code:
The output of the compiler after it translates the program.
executable:
Another name for object code that is ready to be executed.
prompt:
Characters displayed by the interpreter to indicate that it is ready to take input from the user.
script:
A program stored in a file (usually one that will be interpreted).
interactive mode:
A way of using the Python interpreter by typing commands and expressions at the prompt.
script mode:
A way of using the Python interpreter to read and execute statements in a script.
program:
A set of instructions that specifies a computation.
algorithm:
A general process for solving a category of problems.
bug:
An error in a program.
debugging:
The process of finding and removing any of the three kinds of programming errors.
syntax:
The structure of a 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.
natural language:
Any one of the languages that people speak that evolved naturally.
formal language:
Any one of the languages that people have designed for specific purposes, such as representing mathematical ideas or computer programs; all programming languages are formal languages.
token:
One of the basic elements of the syntactic structure of a program, analogous to a word in a natural language.
parse:
To examine a program and analyze the syntactic structure.
print statement:
An instruction that causes the Python interpreter to display a value on the screen.
problem solving 问题求解:
把问题表述清楚、找到解法并表达出解法的过程。
high-level language 高级语言:
像 Python 这样、为人类易于读写而设计的编程语言。
low-level language 低级语言:
为计算机易于执行而设计的编程语言;也称「机器语言」或「汇编语言」。
portability 可移植性:
程序能在不止一种计算机上运行的性质。
interpret 解释:
通过逐行翻译来执行高级语言编写的程序。
compile 编译:
一次性将高级语言编写的程序翻译成低级语言,以备后续执行。
source code 源代码:
编译之前的高级语言程序。
object code 目标代码:
编译器翻译程序后产生的输出。
executable 可执行文件:
已准备好被执行的目标代码的另一种叫法。
prompt 提示符:
解释器显示的字符,表示它已准备好接收用户输入。
script 脚本:
存储在文件中的程序(通常是会被解释执行的那种)。
interactive mode 交互模式:
在提示符下键入命令和表达式来使用 Python 解释器的方式。
script mode 脚本模式:
用 Python 解释器读取并执行脚本中语句的方式。
program 程序:
一组规定了某次计算的指令。
algorithm 算法:
解决某一类问题的通用过程。
bug 缺陷:
程序中的一个错误。
debugging 调试:
查找并消除三类编程错误中任何一类的过程。
syntax 语法:
程序的结构。
syntax error 语法错误:
程序中导致无法解析(因而也无法解释执行)的错误。
exception 异常:
在程序运行过程中被检测到的错误。
semantics 语义:
程序的含义。
semantic error 语义错误:
使程序做出程序员本意之外之事的错误。
natural language 自然语言:
人们所说的、自然演化的任何一种语言。
formal language 形式语言:
人们为特定目的设计的任何一种语言,例如表示数学思想或计算机程序;所有编程语言都是形式语言。
token 标记:
程序语法结构的基本元素之一,类似于自然语言中的单词。
parse 解析:
检查程序并分析其语法结构。
print statement 打印语句:
让 Python 解释器在屏幕上显示一个值的指令。

1.8 Exercises 1.8 习题

Exercise 2

习题 2

Use a web browser to go to the Python website 1 + 10030. This page contains information about Python and links to Python-related pages, and it gives you the ability to search the Python documentation.

用网页浏览器打开 Python 网站 1 + 10031。这个页面包含关于 Python 的信息,并有指向 Python 相关页面的链接,还能让你搜索 Python 文档。

For example, if you enter 1 + 1 in the search window, the first link that appears is the documentation of the 1 + 1 statement. At this point, not all of it will make sense to you, but it is good to know where it is.

例如,如果你在搜索框里输入 1 + 1,出现的第一条链接就是 1 + 1 语句的文档。此刻你未必全看得懂,但知道它在哪很有好处。

Exercise 3

习题 3

Start the Python interpreter and type 1 + 10 to start the online help utility. Or you can type 1 + 10037 to get information about the 1 + 1 statement.

启动 Python 解释器,键入 1 + 10 来开启在线帮助工具。或者,你也可以键入 1 + 10040 来获取关于 1 + 1 语句的信息。

If this example doesn’t work, you may need to install additional Python documentation or set an environment variable; the details depend on your operating system and version of Python.

如果这个例子跑不通,你可能需要安装额外的 Python 文档,或者设置一个环境变量;具体细节取决于你的操作系统和 Python 版本。

Exercise 4

习题 4

Start the Python interpreter and use it as a calculator. Python’s syntax for math operations is almost the same as standard mathematical notation. For example, the symbols 2, 2 and 2 denote addition, subtraction and division, as you would expect. The symbol for multiplication is 2.

启动 Python 解释器,把它当计算器用。Python 的数学运算语法几乎和标准数学记法一样。例如,符号 222 分别表示你预期的加、减、除。乘法的符号是 2

If you run a 10 kilometer race in 43 minutes 30 seconds, what is your average time per mile? What is your average speed in miles per hour? (Hint: there are 1.61 kilometers in a mile).

如果你以 43 分 30 秒跑完一场 10 公里比赛,那么你平均每英里用时多少?平均时速是多少英里每小时?(提示:1 英里等于 1.61 公里)。