Selection
Python for AP CS Principles Lesson 6 2:09 English narration · English + 中文 subtitles burned in
Chapters
Transcript
Selection means the program picks what to do based on a condition.
选择的意思是,程序根据一个条件来决定做什么。
And an if-elif-else is a chain, not three separate questions — watch what happens with the hour set to fourteen.
而 if-elif-else 是一条"链",不是三个各自独立的问题—— 看看把 hour 设成 14 时会发生什么。
First: is fourteen less than twelve?
先问:14 小于 12 吗?
No, so move on.
不是,往下走。
Then the elif: is it less than eighteen?
再问 elif:小于 18 吗?
That one is true, so Afternoon prints.
这一条是真的,于是打印 Afternoon。
And the else was never even asked, because the chain stopped the moment something matched.
而那个 else 根本没被问到, 因为一旦有一条匹配上,这条链就停住了。
A condition is not special syntax — it is just a value.
条件不是什么特殊语法——它就是一个值。
Print a comparison and you see it: score greater-or-equal fifty gives True or False, a real value you could store.
把一个比较打印出来,你就看见了: score >= 50 给出 True 或 False,是一个你甚至可以存起来的真实的值。
And here is the slip that costs marks every year: a double equals TESTS whether two things are the same, while a single equals stores a value into a variable.
而下面这个失误每年都在丢分: 双等号是在"测试"两样东西是不是一样, 而单个等号是把一个值"存进"变量里。
Boolean operators let one condition ask two things at once.
布尔运算符让一个条件一次问两件事。
and is True only when both sides are True — and on a number line that is a band, the overlap of the two tests.
and 只有当两边都为真时才为真—— 而在数轴上,那就是一段区间,是两个测试重叠的部分。
Sixteen falls inside it, so this counts as a teenager.
16 落在里面,所以它算是青少年。
or is easier on you: it needs at least one side to be true.
or 就宽松些:它只要求至少有一边为真。
And not simply flips the answer over.
而 not 只是把答案翻过来。
On the exam the same thing is written with braces instead of indentation.
在考卷上,同样的东西是用花括号写的,而不是靠缩进。
IF with the condition in brackets, then a pair of braces around what runs, then ELSE with its own braces.
IF 后面把条件放在圆括号里, 再用一对花括号把要执行的内容括起来, 然后是 ELSE,也有自己的花括号。
And the logic words go in capitals: AND, OR, NOT.
而逻辑词要大写:AND、OR、NOT。
Four things to take with you.
带走四点。
One: selection chooses a branch from a True or False test.
第一:选择根据一个真假测试来挑一条分支。
Two: an elif is only reached when everything above failed.
第二:只有上面全都不成立时,才会问到 elif。
Three: compare with a double equals, not a single one.
第三:比较要用双等号,不是单个等号。
Four: and needs both sides; or needs at least one.
第四:and 要两边都真;or 至少一边真就行。
Now write some conditions in the tasks below.
现在去下面的题里写几个条件。