Putting it all together
Python Basics Lesson 15 2:27 English narration · English + 中文 subtitles burned in
Chapters
Transcript
This is the last lesson, and it builds one small tool out of everything so far.
这是最后一课,它要用前面学过的全部内容,做出一个小工具。
You start with one list of scores.
你从一个分数列表开始。
You want to know the average, how many passed, and a short summary of the whole class.
你想知道平均分、有多少人及格, 以及整个班级的一份简短汇总。
So write one small function for each job, keep each one short enough to test on its own, and the three answers fall out.
于是给每件事写一个小函数,每个都短到可以单独测试,三个答案自然就有了。
That is how every real program is put together.
每一个真实的程序,都是这样搭起来的。
Before you write a loop, check whether Python has already written it.
在你动手写循环之前,先看看 Python 是不是已经替你写好了。
For a list of numbers there are four you will use constantly: len and sum give you how many and their total, so an average is one line.
对一个数字列表,有四个你会经常用到:len 和 sum 给你个数和总和, 所以求平均只要一行。
Max and min give you the largest and smallest without a loop and without a starting value to get wrong.
max 和 min 给你最大值和最小值, 不需要循环,也不需要担心初始值取错。
Writing your own is not wrong — it is just work you did not need to do.
自己写一个并没有错——只是那是你本来不必做的活。
One job has no built-in, and it comes up constantly: counting the items that pass some test.
有一件事没有现成的函数,而它又不断出现:数出满足某个条件的项有多少个。
The shape is always the same.
结构永远是一样的。
A counter at zero before the loop, a loop over the items, an if inside, and add one when it is true.
循环之前把计数器设成 0,遍历各项,里面放一个 if, 条件为真就加 1。
Then fill in the test for the job at hand — here, is this score at least the pass mark.
然后把这次要用的条件填进去—— 这里就是:这个分数有没有达到及格线。
Learn the shape once and you have written this function forever.
把这个结构学会一次,你就等于永远写好了这个函数。
Now the last task of the course.
现在是这门课的最后一道题。
It wants one function that hands back three keys: the highest, the lowest and the average.
它要一个函数,交回三个键: 最高分、最低分和平均分。
Each one is a built-in you just met, and they go straight into a dictionary.
每一个都是你刚认识的内置函数, 它们直接放进一个字典里。
Return that dictionary, and the caller can ask for whatever field they want by name.
把这个字典返回出去, 调用者就可以按名字取他想要的任何一项。
This is how a function gives back more than one thing — not three returns, one record.
一个函数要交还不止一样东西时,就是这么做的——不是三个 return,而是一条记录。
Four things from this lesson, and then you are done.
这一课有四点,然后你就学完了。
One: one function, one job — then combine them.
第一:一个函数只做一件事——然后把它们组合起来。
Two: len, sum, max and min save you a loop.
第二:len、sum、max 和 min 能省掉一个循环。
Three: count-the-ones-that-pass is a pattern you will reuse for years.
第三:“数出满足条件的项”是一个你今后很多年都会用到的模式。
Four: build a piece, test it, and only then add the next.
第四:写一小块,测一小块,然后再加下一块。
As for where to go next: the exam courses take these same ideas into IGCSE and A-Level, and JavaScript, C and SQL all start from what you now know.
至于接下来去哪里:考试课程会把这些相同的思想带进 IGCSE 和 A-Level, 而 JavaScript、C 和 SQL 都从你现在会的东西起步。
Well done.
做得好。