Procedures and abstraction
Python for AP CS Principles Lesson 8 1:49 English narration · English + 中文 subtitles burned in
Chapters
Transcript
A procedure is a named block of code you can use again and again.
过程是一段有名字的代码,你可以反复使用它。
In Python you make one with def, then a name, then brackets, and the code goes indented underneath.
在 Python 里你用 def 来定义,然后是名字,然后是括号, 代码缩进写在下面。
Defining it does not run it — you call it by writing its name.
定义并不会执行它——你要写出它的名字来"调用"它。
Call it twice and you get two hellos.
调用两次,你就得到两句 Hello。
The brackets are the part that actually runs it.
括号才是真正让它跑起来的那一部分。
Now the two things a procedure does with data.
现在说过程对数据做的两件事。
A parameter is a value it receives: write the name in the brackets, and when you call square of five, the five goes in as the parameter.
参数是它"收到"的值:把名字写在括号里, 当你调用 square(5) 时,那个 5 就作为参数走了进去。
Then return sends a value out — twenty five comes back to whoever called it.
然后 return 把一个值送出来—— 25 回到了调用它的那一方手上。
And after return runs, the procedure stops immediately.
而 return 一执行,过程立刻就结束了。
And this is why AP calls it abstraction.
而这正是 AP 把它叫作"抽象"的原因。
Look at the call on the left: it works perfectly well without you knowing a single thing about what is inside the box.
看左边那个调用: 哪怕你对盒子里面一无所知,它照样跑得好好的。
Abstraction means hiding the detail behind a simple name — which makes code shorter, clearer, and easy to reuse.
抽象的意思,就是把细节藏在一个简单的名字后面—— 这让代码更短、更清楚,也更容易复用。
In exam pseudocode the same procedure is written with the word PROCEDURE where Python writes def, braces instead of indentation, and RETURN in capitals — and on the exam RETURN takes brackets round the value.
在考试伪代码里,同样的过程是这样写的: 用 PROCEDURE 这个词代替 Python 的 def, 用花括号代替缩进, RETURN 大写—— 而且在考卷上,RETURN 要给值加上圆括号。
Four things to take with you.
带走四点。
One: a procedure is a named block you can reuse.
第一:过程是一段你可以复用的、有名字的代码。
Two: a parameter carries a value into it.
第二:参数把一个值带进去。
Three: return carries a value back out, and stops it.
第三:return 把一个值带出来,并且让它就此停下。
Four: abstraction hides the detail behind a simple name.
第四:抽象把细节藏在一个简单的名字后面。
Now write a few procedures in the tasks below.
现在去下面的题里写几个过程。