Skip to content

Programming Fundamentals

University Computer Science Topic 1 6:37 English narration · English and 中文 subtitles you can switch

space play · ←/→ 5s · j/l 10s · f fullscreen · c subtitles · ,/. speed

Chapters

Transcript
Every program in this course is complete and runnable: type it, run it, then change one line. 本课程中的每个程序都是完整且可运行的:输入代码,运行,然后修改其中一行。
The whole skill is a loop. 整项技能就是一个循环。
First predict what the code will do, then run it and compare. 先预测代码会做什么,再运行并比较结果。
The gap between your prediction and the real output is exactly the gap in your mental model, and that is where learning happens. 你的预测与实际输出之间的差距,正是你头脑中的模型存在的不足,而这正是学习发生的地方。
Every value has a type: integer, float, string or boolean, and the type decides which operations work. 每个值都有类型:整数、浮点数、字符串或布尔值,类型决定了哪些运算可以进行。
The string 4 plus the string 2 gives 42; the number 4 plus 2 gives 6; and the string 4 plus the number 2 is a TypeError, because Python never guesses. 字符串 4 加字符串 2 得到 42;数字 4 加 2 得到 6;而字符串 4 加数字 2 会产生 TypeError,因为 Python 从不猜测。
The input function always returns a string, so convert it deliberately. input 函数总是返回字符串,所以要有意识地进行类型转换。
Picture names as tags on boxes of value. 把名称想象成贴在值的盒子上的标签。
An expression reads boxes and makes a new box; assignment just moves a tag. 表达式读取盒子并创建一个新盒子;赋值只是移动标签。
So int of the input times 3.50 makes a brand-new float box, and the till prints 21.0, where the point zero shows the type. 因此,输入值经 int 转换后乘以 3.50,会创建一个全新的浮点数盒子,收银程序输出 21.0,其中小数点后的零表明了类型。
Assignment never edits a box in place, which prevents a lot of confusion later. 赋值从不会直接修改盒子里的值,这能避免以后产生很多混淆。
An if, elif, else chain tests from top to bottom and runs only the first true branch. if、elif、else 分支链从上到下依次判断,只执行第一个条件为真的分支。
At the cinema, under-twelves and over-65s pay 5, students pay 7, and everyone else 10. 在电影院,12 岁以下和超过 65 岁的人付 5,学生付 7,其他人付 10。
Because the age test comes first, a 70-year-old student pays 5. 由于先判断年龄,一名 70 岁的学生付 5。
Swap the branches and the same person pays 7: the order is the policy. 交换分支顺序,同一个人就要付 7:顺序决定了收费规则。
Follow the 70-year-old student through this flowchart. 跟着这名 70 岁的学生走一遍流程图。
The age test is true, so that branch runs, and the student branch is never even reached. 年龄判断为真,因此执行该分支,甚至不会进入学生分支。
Exactly one branch runs. 恰好只有一个分支会执行。
Two more traps: a double equals sign compares while a single one assigns, and 0.1 plus 0.2 does not exactly equal 0.3, so compare floats with a small tolerance. 还有两个陷阱:双等号用于比较,单等号用于赋值;0.1 加 0.2 并不精确等于 0.3,因此比较浮点数时要允许一个很小的误差。
The decision tests whether age is at least 18. 这个判断检查 age 是否至少为 18。
If it is true, the program outputs Adult; if false, Minor. 如果为真,程序输出“成年人”;如果为假,输出“未成年人”。
Exactly one branch runs, and both rejoin before the end, so the rest of the program carries on the same way. 恰好执行一个分支,两个分支在结束前重新汇合,因此程序的其余部分会以相同方式继续运行。
Use a for loop when you know how many times to repeat, and a while loop when a condition decides. 知道需要重复多少次时,使用 for 循环;由条件决定时,使用 while 循环。
Summing 1 to 100 with a for loop gives 5050. 用 for 循环将 1 加到 100,得到 5050。
Every while loop needs a start, a condition and a step towards stopping, or it never ends. 每个 while 循环都需要初始状态、条件,以及使其逐步停止的操作,否则循环永远不会结束。
A trace table follows each variable round by round, so you can check the loop. 跟踪表逐轮记录每个变量的变化,让你检查循环。
Here is the factorial loop as a trace table. 这里是阶乘循环的跟踪表。
Round by round, n counts down while the product grows: 5, then 20, then 60, then 120, and after four passes the condition fails. 每一轮中,n 递减,而乘积逐渐增大:先是 5,然后是 20、60、120,经过四轮后条件不再成立。
Fill the table by hand first, then add a print inside the loop and let Python grade you. 先手工填写表格,再在循环中加入一条 print,让 Python 为你检查。
Where they disagree is exactly where your model breaks. 两者不一致的地方,正是你的理解出现问题的地方。
Before the loop, total and count are both 0. 循环开始前,total 和 count 都是 0。
The first value, 4, makes total 4 and count 1. 第一个值 4 使 total 变为 4,count 变为 1。
Then 7 makes total 11 and count 2. 接着 7 使 total 变为 11,count 变为 2。
Then 5 makes total 16 and count 3. 然后 5 使 total 变为 16,count 变为 3。
A trace table records every variable after every pass, so errors show up at once. 跟踪表记录每一轮之后每个变量的值,因此错误会立刻显现。
A function packages a job behind a name: parameters go in, and a return value comes out. 函数将一项任务封装在一个名称之下:传入参数,返回一个值。
Printing is not returning; a function with no return gives back None. 打印不等于返回;没有 return 的函数会返回 None。
Add fee returns the amount plus 3, and order total returns add fee of unit times quantity, so order total of 250 and 4 gives 1003. 加费用函数返回金额加 3,而订单总额函数返回将单价乘以数量后传给加费用函数所得到的结果,因此用 250 和 4 调用订单总额函数得到 1003。
Each call has its own local names. 每次调用都有各自的局部名称。
Follow the nested calls. 跟踪这些嵌套调用。
The print statement calls order total, which pauses while add fee runs with 1000. print 语句调用 order_total,后者暂停,等待 add_fee 以 1000 为参数运行。
Add fee returns 1003, which travels back along the chain to be printed. add_fee 返回 1003,这个值沿调用链传回并被打印。
The caller waits, the callee works, and the value lands. 调用者等待,被调用者执行,最后返回值到达。
Once you see this stack of waiting callers, nested functions stop being magic. 一旦看清这层层等待的调用栈,嵌套函数就不再神秘了。
Each collection has a job: a list keeps order, a dictionary looks things up, a tuple holds fixed parts and a set keeps items unique. 每种集合都有自己的用途:列表保持顺序,字典用于查找,元组存放固定的组成部分,集合保证元素唯一。
To count items, use a dictionary keyed by the item. 要统计元素出现的次数,可以用元素作为字典的键。
Two traps: if b equals a, both names share one list, so appending through b changes a too. 有两个陷阱:如果 b 等于 a,两个名称就共享同一个列表,因此通过 b 追加元素也会改变 a。
And never remove items from a list while looping over it. 另外,绝不要在遍历列表时从中删除元素。
Two tags, one box: after b equals a, appending 2 through b means a also reads 1, 2. 两个标签,一个盒子:在 b 等于 a 之后,通过 b 追加 2,读取 a 时也会得到 1、2。
Assignment shares; it never copies. 赋值会共享对象,从不会复制对象。
When you need an independent list, copy it with a slice. 需要独立列表时,可以用切片复制。
The same picture explains why removing items during a loop skips some, so loop over a snapshot copy instead. 同一幅图也解释了为什么循环时删除元素会跳过一些元素,所以应当遍历一份快照副本。
Open files with a with block, which closes the file whatever happens. 用 with 代码块打开文件,无论发生什么,它都会关闭文件。
Mode w empties the file first, while mode a appends to it. 模式 w 会先清空文件,而模式 a 会在文件末尾追加内容。
Catch only the exceptions you can respond to, by name. 只按名称捕获你能处理的异常。
If the settings file is missing, use a default size of 12; if it holds a word instead of a number, catch the ValueError too. 如果设置文件不存在,就使用默认大小 12;如果其中是单词而不是数字,也要捕获 ValueError。
Let unexpected errors crash loudly. 让意料之外的错误明确地导致程序崩溃。
This is the red, green, refactor loop. 这就是红、绿、重构循环。
Write a test that fails, and check that it fails for the right reason. 先写一个失败的测试,并确认它失败的原因正确。
Then write just enough code to make it pass. 然后只写足够让测试通过的代码。
Then tidy the code while the tests hold its behaviour in place. 接着整理代码,同时用测试确保其行为不变。
In the discount example, the middle test, expecting 902, caught a real mistake in the first draft. 在折扣示例中,中间那个预期结果为 902 的测试发现了初稿中的一个真实错误。
Give each function one job, and test it the moment it exists: with zero, with one, and with one awkward case. 让每个函数只负责一项任务,并在函数写出来后立即测试:用零、用一,再用一个棘手的例子。
For example, order total of 250 and 0 should still return the 3 fee. 例如,用 250 和 0 调用 order_total,仍应返回 3 的费用。
To debug, reproduce the problem small, inspect halfway, and fix one thing at a time. 调试时,先用小规模的例子重现问题,再检查中间状态,每次修复一个问题。
Each inspection halves the search. 每次检查都将搜索范围缩小一半。
Now test yourself, then run each one. 现在先自测,再运行每个例子。
What do 7 integer-divided by 2 and 7 modulo 2 give? 7 整除 2 和 7 对 2 取余分别得到什么?
If you halve 100 with integer division until you reach 1, how many times does the loop run? 如果用整数除法不断将 100 减半,直到得到 1,循环会运行多少次?
What does order total of 250 and 0 return when there is a fee of 3? 费用为 3 时,用 250 和 0 调用 order_total 会返回什么?
Pause, predict, then run it. 暂停,预测,然后运行验证。

Comments

    Log in or create account

    IGCSE, A-Level & AP