Programming
IGCSE Computer Science Topic 8 13:16 English narration · English + 中文 subtitles burned in
Chapters
Transcript
Here is a short program.
这是一小段程序。
It reads five test marks and prints the total.
它读入五个考试分数,然后输出总分。
The five marks are eight, nine, seven, six and ten, so the total should be forty.
这五个分数是八、九、七、六和十,所以总分应该是四十。
Watch what the computer actually prints.
看看计算机真正输出了什么。
Ten.
十。
Not forty.
不是四十。
Nothing is broken: the computer did exactly what it was told, and what it was told was wrong.
程序没有坏:计算机完全照着指令做了,只是指令本身写错了。
One line is in the wrong place.
有一行放错了位置。
By the end of this lesson you will find it in a second.
学完这一课,你一秒钟就能找出它。
Programming.
程序设计。
Today: variables and data types, the three structures, selection and loops, totalling and trace tables, operators, strings, subroutines, arrays and files.
今天我们讲:变量和数据类型,三种结构,选择与循环, 求和与追踪表,运算符、字符串、子程序、数组,还有文件。
Then we fix that broken program.
最后我们把那段出错的程序改好。
A variable is a named store, and its value can change while the program runs.
变量是一个有名字的存储位置,它的值在程序运行时可以改变。
Picture a box with a name on it.
想象一个写着名字的盒子。
This box is called age, and right now it holds sixteen; next year it can hold seventeen.
这个盒子叫 age,此刻它装着十六;明年它可以装十七。
A constant is a named store too, but its value never changes, like the number pi.
常量也是有名字的存储位置,但它的值永远不变,比如圆周率。
Declare each one before you use it.
使用之前,要先声明它们。
While the program is running, every variable and constant lives in the computer's memory, called RAM.
程序运行的时候,每个变量和常量都住在计算机的内存里,也就是随机存取存储器。
The name is a label on a slot; the value is what sits in that slot.
名字是插槽上的标签;值就是插槽里放的东西。
When the program stops, those slots are cleared, which is why you need a file if you want data to survive.
程序一停,这些插槽就被清空,所以如果想让数据留下来,就需要文件。
RAM is fast working space, not long-term storage.
内存是快速的工作空间,不是长期存储。
You declare a variable by writing DECLARE, then its name, then its type.
声明变量的写法是:先写 DECLARE,再写名字,再写类型。
DECLARE score as INTEGER means score will only hold whole numbers.
把 score 声明为整数,表示它只能装整数。
DECLARE name as STRING means name will hold a row of characters.
把 name 声明为字符串,表示它装一串字符。
A constant is different: CONSTANT Pi equals three point one four two, and that value is fixed for the whole program.
常量不同:常量圆周率等于三点一四二,整个程序里这个值都固定不变。
Write the declarations before you use the names, or the computer does not know what the name is allowed to hold.
要在使用这些名字之前先写好声明,否则计算机不知道这个名字允许装什么。
What kind of value a store holds is its data type, and you must know five.
一个存储位置能放什么样的值,这叫做数据类型,你必须掌握五种。
An integer is a whole number, like seven.
整数是没有小数部分的数,比如七。
A real number has a decimal point.
实数带小数点。
A char is one single character.
字符是单独的一个字符。
A string is a row of characters.
字符串是一串字符。
And a Boolean is only ever true or false.
而布尔值只能是真或假。
The wrong type quietly loses information.
类型选错了,程序就会悄悄丢掉信息。
Input and output are how a program talks to a person.
输入和输出,是程序和人说话的方式。
Output shows a value on the screen.
输出把一个值显示在屏幕上。
Input reads a value from the user and stores it in a variable.
输入从用户那里读进一个值,并把它存进变量。
Always output a prompt first, so the user knows what to type.
一定要先输出一句提示,这样用户才知道该输入什么。
Here the program asks for a name, then reads it into the variable name.
这里程序先问名字,再把读到的内容存进变量 name。
Type Ada.
输入 Ada。
Then output can print two items: the text Hello, then the name that was just stored.
然后输出可以打印两项:文字 Hello,以及刚存好的名字。
The screen says Hello, Ada.
屏幕上显示:Hello,Ada。
Now the shape of a program.
接下来看程序的结构。
Every program is built from three control structures.
每个程序都由三种控制结构搭成。
Sequence: the steps run one after another, top to bottom.
顺序:各个步骤一个接一个,从上到下执行。
Selection: the program tests something and chooses a branch.
选择:程序做一个判断,然后选择走哪一条分支。
Iteration: the program repeats a group of steps while a test says carry on.
迭代:只要判断说继续,程序就把一组步骤反复执行。
Sequence is the simplest structure, and almost every short program starts with it.
顺序是最简单的结构,几乎每个短程序都从它开始。
Read the length.
读入长度。
Read the width.
读入宽度。
Multiply them and store the answer in area.
把它们相乘,把答案存进面积。
Then output area.
然后输出面积。
Four lines, top to bottom, no choices and no repeats.
四行,从上到下,没有选择,也没有重复。
If you swap the multiply line with the output line, the area is not ready yet, and the program prints the wrong thing.
如果你把相乘那一行和输出那一行对调,面积还没算好,程序就会打印错误的结果。
Order matters.
顺序很重要。
Selection uses an IF statement.
选择用 IF 语句实现。
If the score is fifty or more, print Pass; otherwise print Fail.
如果分数大于或等于五十,就输出 Pass;否则输出 Fail。
Send in seventy-two: the test is true, so only the first branch runs.
送进七十二:判断为真,所以只有第一条分支执行。
Send in forty: only the second branch runs.
送进四十:只有第二条分支执行。
One runs, never both.
两条只会执行一条,绝不会都执行。
With many choices, a CASE statement is tidier.
当选项很多时,用 CASE 语句更整齐。
And you may put one structure inside another.
你还可以把一种结构放进另一种结构里面。
That is nesting: here an IF sits inside a FOR loop, so every pass tests the counter and prints odd or even.
这就是嵌套: 这里 IF 放在 FOR 循环里面,所以每一轮都会判断计数器,输出奇数还是偶数。
A nested statement is one control structure placed inside another.
嵌套语句,就是把一种控制结构放进另一种控制结构里面。
You can nest selection inside iteration, or the other way round.
你可以把选择嵌进迭代里,也可以反过来。
Watch this: a FOR loop from one to three, and inside it an IF.
看这个:一个从一到三的 FOR 循环,里面放着一个 IF。
The IF asks whether i MOD two equals zero — that is the even test.
IF 判断 i 对二取余是否等于零——这就是在测偶数。
First pass, i is one: one is odd, so it prints odd.
第一轮,i 是一:一是奇数,所以输出奇数。
Second pass, i is two: two is even, so it prints even.
第二轮,i 是二:二是偶数,所以输出偶数。
Third pass, i is three: odd again.
第三轮,i 是三:又是奇数。
Selection and iteration working together.
选择和迭代一起工作。
You will not have to write more than three levels of nesting in the exam.
考试里你不必写超过三层的嵌套。
A loop comes in three kinds.
循环有三种。
A count-controlled loop, written with FOR, repeats a fixed number of times.
计数循环用 FOR 写,重复固定的次数。
A pre-condition loop, written with WHILE, is on the left: the test comes before the body, so the body may run zero times.
前测循环用 WHILE 写,在图的左边:判断在循环体之前, 所以循环体可能执行零次。
A post-condition loop, written with REPEAT UNTIL, is on the right: the test comes after the body, so the body always runs at least once.
后测循环用 REPEAT UNTIL 写,在图的右边:判断在循环体之后, 所以循环体至少执行一次。
So which loop do you choose?
那么该选哪种循环?
Both of these loops ask for a password until it is correct.
这两个循环都在反复要求输入密码,直到密码正确。
Now suppose the password is already correct before the loop starts.
现在假设在循环开始之前,密码已经是正确的。
The WHILE loop tests first and skips the body completely: zero passes.
WHILE 循环先判断,然后完全跳过循环体:执行零次。
The REPEAT loop asks once, then tests: one pass. So here is the rule.
REPEAT 循环先问一次,然后才判断:执行一次。
Passes known, use FOR. Maybe zero, use WHILE. At least one, use REPEAT.
所以规则是:次数已知,用 FOR;可能一次都不用,用 WHILE;至少一次,用 REPEAT。
Two short patterns show up in almost every loop.
几乎每个循环里都会出现两个短套路。
Counting adds one to a counter each time: count gets count plus one.
计数:每次给计数器加一,计数变成计数加一。
Totalling adds a new value to a running sum: total gets total plus value.
求和:每次把新值加进累加和,总数变成总数加新值。
Set both to zero before the loop starts.
循环开始前,先把两者都设为零。
Then every pass updates them.
然后每一轮都更新它们。
After the loop, the counter is how many items you saw, and the total is their sum.
循环结束后,计数器是你见过多少项,总数是它们的和。
Two patterns live inside almost every loop.
几乎每个循环里都藏着两个套路。
Totalling: keep a running total, and add each new value to it.
求和:维护一个累加的总数,每次把新的值加进去。
Counting: keep a counter, and add one each time.
计数:维护一个计数器,每次加一。
Before the loop starts, set both of them to zero.
在循环开始之前,要把它们两个都设为零。
Examiners test this with a trace table: one column for each variable, one row for each pass.
考官用追踪表来考这一点:每个变量一列,每一轮一行。
Our loop reads four, seven and five.
我们的循环读入四、七和五。
First pass: the total becomes four, the count becomes one.
第一轮:总数变成四,计数变成一。
Second pass: eleven, and two.
第二轮:十一,和二。
Third pass: sixteen, and three.
第三轮:十六,和三。
The last row is your answer.
最后一行就是你的答案。
Now the program from the start of the lesson.
现在回到这节课开头的那段程序。
Read five marks, then print the total and the average.
读入五个分数,然后输出总分和平均分。
Set the total to zero.
先把总数设为零。
Then loop five times: read a mark, and add it to the total.
然后循环五次:读入一个分数,把它加到总数上。
After the loop, divide the total by five and print both numbers.
循环结束后,用总数除以五,再把两个数都输出。
Two lines carry the marks.
这里有两行是得分点。
Setting the total to zero must sit before the loop; put it inside instead, and the total is wiped on every pass, which is exactly why our program printed ten, the last mark.
把总数设为零这一行,必须放在循环之前; 如果把它放进循环里面,总数每一轮都会被清空—— 这正是我们那段程序输出十(最后一个分数)的原因。
Set up before, calculate after.
循环前初始化,循环后再计算。
Assignment uses a left arrow.
赋值用一个左箭头。
Read it from right to left: work out the right-hand side first, then store that answer in the name on the left.
要从右往左读:先算出右边,再把答案存进左边的名字。
So total gets total plus one.
所以,总数变成总数加一。
If total held seven, the right-hand side is eight, and eight goes back into the same box.
如果总数原来是七,右边就是八,八又存回同一个盒子。
That is how a counter grows.
计数器就是这样长大的。
Likewise, average gets total divided by five.
同样,平均分变成总数除以五。
One warning: the left-hand name is a destination.
一句提醒:左边的名字是存放的目的地。
The arrow is never a test for equality.
这个箭头绝不是在判断两边是否相等。
Operators come in three families.
运算符分成三类。
Arithmetic operators work on numbers: add, subtract, multiply, divide and raise to a power.
算术运算符作用于数字:加、减、乘、除,以及乘方。
DIV gives the whole-number part, so seventeen DIV five is three.
DIV 取除法的整数部分,所以十七 DIV 五等于三。
MOD gives the remainder, so seventeen MOD five is two.
MOD 取余数,所以十七 MOD 五等于二。
Relational operators compare two values and give true or false.
关系运算符比较两个值,返回真或假。
Logical operators join conditions: AND, OR and NOT.
逻辑运算符把条件连接起来:AND、OR 和 NOT。
Relational operators compare two values: equals, less than, greater than, less than or equal, greater than or equal, and not equal.
关系运算符比较两个值:等于、小于、大于、小于等于、大于等于,以及不等于。
The answer is always true or false.
答案永远是真或假。
Logical operators join those answers.
逻辑运算符把这些答案连接起来。
AND needs both sides true.
AND 要求两边都为真。
OR needs at least one side true.
OR 要求至少一边为真。
NOT flips true to false and false to true.
NOT 把真变成假、假变成真。
So if age is at least thirteen AND age is at most nineteen, the program prints Teenager.
所以如果年龄至少十三并且至多十九,程序就输出 Teenager。
Both comparisons must pass.
两个比较都必须通过。
A string is a row of characters, and four operations come up again and again.
字符串是一串字符,有四个操作会反复出现。
LENGTH gives the number of characters, so the word Computer has length eight.
LENGTH 给出字符的个数,所以单词 Computer 的长度是八。
SUBSTRING pulls a smaller part out: the first four characters of Computer are C, O, M, P.
SUBSTRING 取出其中一小段:Computer 的前四个字符是 C、O、M、P。
UCASE changes letters to upper case, to capitals; LCASE changes them to lower case, to small letters.
UCASE 把每个字母变成大写;LCASE 把每个字母变成小写。
On your paper the first character is at position one, but in Python it is position zero.
在你的试卷上,第一个字符的位置是一;而在 Python 里,它的位置是零。
A library routine is ready-made code you can call without writing it yourself.
库程序是现成的代码,你不用自己写就可以调用。
MOD and DIV you already met: remainder and whole-number part.
取余和整除你已经见过:一个取余数,一个取整数部分。
ROUND takes a real number and rounds it to a set number of decimal places.
四舍五入接收一个实数,并按给定的小数位数把它圆整。
RANDOM gives a random number, which is useful for games and for sampling.
随机数给出一个随机数,对游戏和抽样很有用。
Use the exact names on the paper.
要用试卷上印的那个确切名字。
Do not invent your own spelling in the exam.
考试里不要自己发明拼写。
When the same job appears again and again, give it a name.
当同样的工作反复出现时,就给它起个名字。
A procedure does an action and gives nothing back: calling Greet with the name Ada prints Hello, Ada.
过程只做一个动作,不返回任何值:用名字 Ada 调用 Greet,它输出 Hello, Ada。
A function returns a value to where it was called: Square of five returns twenty-five, so you can store that answer or use it in a bigger expression.
函数会把一个值返回到调用它的地方:Square 传入五,返回二十五, 所以你可以把这个答案存起来,或者用在更大的表达式里。
The value you pass in arrives in a parameter, and you may use up to three.
你传进去的值,会被接收到参数里,最多可以用三个参数。
A local variable is declared inside a procedure or a function, and it only exists there: the rest of the program cannot see it, and the moment that block finishes it is gone.
局部变量声明在过程或函数的内部,它只存在于那里: 程序的其他部分看不到它;而且那个代码块一结束,它就消失了。
A global variable is declared in the main program, so every part of the program can change it.
全局变量声明在主程序里,所以程序的每一部分都能改动它。
Globals sound easier, but any block can change one by accident.
全局变量听起来更方便,但任何一个代码块都可能不小心把它改掉。
A maintainable program is one another person can read and change without fear.
可维护的程序,是指别人能够放心地读懂并修改的程序。
Use meaningful identifiers: call it totalScore, not x.
使用有意义的标识符:叫它 totalScore,不要叫 x。
Add comments that explain why the code is there, not what is obvious.
加上注释,解释这段代码为什么在这里,而不是重复显而易见的内容。
And split the work into procedures and functions, so each block does one clear job.
并且把工作拆分到过程和函数里,让每个代码块只做一件清楚的事。
An array is a single variable that holds many values of the same type.
数组是一个变量,却能存放许多同一类型的值。
Each value has an index, a position number, and that is how you reach it.
每个值都有一个索引,也就是位置编号,你就靠它取到那个值。
Here five scores live in one array called scores, and the value at index two is seventy-five.
这里,五个分数放在一个叫 scores 的数组里,索引为二的那个值是七十五。
A two-dimensional array is a table, with rows and columns, so it needs two indexes: the row first, then the column.
二维数组是一张表格,有行也有列,所以需要两个索引:先行,后列。
One FOR loop can fill a whole list; to reach every cell of a table, you put one loop inside another.
一个 FOR 循环就能填满一张列表;要访问表格里的每一个格子,就把一个循环放进另一个循环里面。
To fill an array from the user, put INPUT inside a FOR loop.
要从用户填满一个数组,就把输入放进 FOR 循环里。
Loop i from one to five.
让 i 从一循环到五。
On each pass, input the next score into scores at index i.
每一轮,把下一个分数输入到 scores 的索引 i 处。
After five passes, the list holds five values, and you can read any of them by its index.
五轮之后,列表里就有五个值,你可以用索引读出其中任何一个。
The same pattern works for totalling: walk the array once more and add each scores-of-i into a running total.
同样的套路也适用于求和:再走一遍数组,把每个分数加进累加的总数。
One loop fills; another loop uses.
一个循环负责填入;另一个循环负责使用。
When the program stops, everything in memory disappears.
程序一停止,内存里的一切就消失了。
To keep data, write it into a file. Three steps, always in this order.
要保存数据,就把它写进文件。
Open the file, saying whether you want to read or write. Then read or write: a single item, or a whole line of text. Then close the file, every single time.
三个步骤,顺序永远是这样:先打开文件,说明你是要读还是要写; 然后读或者写:可以是单个数据,也可以是一整行文字; 最后关闭文件,每一次都要关。
In Cambridge pseudocode the three steps look like this.
在剑桥伪代码里,这三个步骤长这样。
Open the file for write, write the text Hello into it, then close the file.
为写而打开文件,把文字 Hello 写进去,然后关闭文件。
Later, open the same file for read, read one line into a variable, then close it again.
之后,为读而打开同一个文件,读入一行到变量里,再关闭一次。
You can move single items or whole lines of text.
你可以移动单个数据,也可以移动整行文字。
Never leave a file open: if the program crashes mid-way, unclosed writes can be lost.
永远不要让文件开着不关:如果程序中途崩溃,没关闭的写入可能会丢失。
Three marks students throw away.
三个学生常常白白丢掉的分。
First, a WHILE loop tests before the body, so it may run zero times, while a REPEAT loop tests after, so it always runs at least once.
第一,WHILE 循环在循环体之前判断,所以可能一次都不执行; 而 REPEAT 循环在循环体之后判断,所以至少执行一次。
Second, set the total or the counter to zero before the loop, and do the final calculation after it.
第二,在循环之前把总数或计数器设为零,最后的计算放在循环之后。
Third, a function returns a value and a procedure does not.
第三,函数返回一个值,过程不返回。
Get those three right, and this topic is yours.
把这三点做对,这个专题就是你的了。