Skip to content

Procedures and functions

Python for IGCSE CS Lesson 6 2:14 English narration · English + 中文 subtitles burned in

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

Chapters

Transcript
A function is a named block of code. 函数是一段有名字的代码。
You write it once with def, and then run it whenever you like by writing its name. 你用 def 把它写一次,之后想运行的时候,写它的名字就行。
Here it is called twice, so it prints twice. 这里它被调用了两次,所以打印了两次。
Two things worth noticing: the block does not run at the point where you write it, and the brackets are what call it. 有两点值得注意: 这段代码在你写下它的地方并不会执行, 而括号才是"调用"它的东西。
A name with no brackets just refers to the function; it does not run it. 只写名字不加括号,那只是在指代这个函数,并不会运行它。
A block that always does exactly the same thing is not very useful, so you can pass a value in. 一段永远做同一件事的代码没什么用,所以你可以把值传进去。
The word in the brackets when you define it is the parameter. 定义时括号里的那个词,叫做形参(parameter)。
The value you put in the brackets when you call it arrives as name inside the block — and that value is called the argument. 调用时你放进括号里的值,会以 name 的身份到达函数内部—— 而那个值叫做实参(argument)。
Those are two words the exam uses precisely, so it is worth keeping them apart. 这是考卷会严格区分的两个词,所以值得分清。
Now the distinction the exam actually examines. 现在说考试真正要考的那个区别。
A function hands a value back with return, so the call itself has a value and you can store it in a variable. 函数用 return 把一个值交回去, 所以这次调用本身就是一个值,你可以把它存进变量。
A procedure just does a job — it prints something, or changes something — and hands nothing back, so there is nothing to store. 过程只是做一件事——打印点什么,或者改动点什么—— 它什么都不交回来,所以也没什么可存的。
Python writes def for both, which hides the difference. Python 两者都写 def,这就把区别藏了起来。
The exam has a separate keyword for each, so it does not. 考卷给它们各自一个关键字,所以区别是明摆着的。
The lesson's second task asks for a function that says whether a number is even. 这一课的第二道题,要写一个判断数字是否为偶数的函数。
And there is a neat move here. 这里有一个漂亮的写法。
N mod two equals nought is already a comparison, and a comparison already gives back True or False — so you return it directly. n % 2 == 0 本身就是一次比较, 而比较本身已经给出 True 或 False—— 所以你直接把它 return 出去。
No if needed. 不需要 if。
Writing if that then return True else return False is not wrong, just three lines where one will do. 写成"如果……就 return True,否则 return False"并没有错, 只是用了三行去做一行能做的事。
Four things to take with you. 带走四点。
One: a function is a named block you define once and call by name. 第一:函数是一段有名字的代码,定义一次,之后按名字调用。
Two: a parameter carries a value into the block. 第二:形参把一个值带进这段代码里。
Three: return hands a value back to whoever called it. 第三:return 把一个值交回给调用它的人。
Four: in the exam's words, a FUNCTION returns and a PROCEDURE just does a job. 第四:用考纲的说法,FUNCTION 有返回值,PROCEDURE 只是做事。
Now do the three tasks. 现在去做那三道题。

Log in or create account

IGCSE, A-Level & AP