Selection and conditionals
引入
6:37
编程基础
本课程中的每个程序都是完整且可运行的:输入代码,运行,然后修改其中一行。整项技能就是一个循环。先预测代码会做什么,再运行并比较结果。你的预测与实际输出之间的差距,正是你头脑中的模型存在的不足,而这正是学习发生的地方。
英文讲解 · 可切换中英文字幕
本课内容
| English | 释义 | 拼音 |
|---|---|---|
| program/ˈprəʊɡræm/ | 程序 | chéng xù |
| condition/kənˈdɪʃn/ | 条件 | tiáo jiàn |
| comparisons | 比较运算 | bǐ jiào yùn suàn |
| selection/sɪˈlekʃn/ | 选择 | xuǎn zé |
| boundary/ˈbaʊndəri/ | 边界 | biān jiè |
| input/ˈɪnpʊt/ | 输入 | shū rù |
| syntax error/ˈsɪntæks ˈerə/ | 语法错误 | yǔ fǎ cuò wù |
为什么老年人付了学生价?
- 电影院向儿童和超过65岁的人收取£5,向学生收取£7,向其他所有人收取£10。一名70岁的学生被收取了£7。
- 程序中的每一条规则都是正确的,只是测试规则的顺序错了。这一课将介绍程序如何选择路径,以及为什么顺序是设计的一部分。
条件是一个结果为真或假的问题
- 条件是一个值为
bool的表达式:age >= 65、answer == "y"、n != 0。比较运算符包括<、<=、>、>=、==(等于)和!=(不等于)。 - 用
and(两者都必须为真)、or(至少一个为真)和not(取反)连接条件。3 >= 3 and not (2 > 5)的结果是True。
# already a bool
student = input("Student? y/n ") == "y"
# prints <class 'bool'>
print(type(student))
What does print(3 >= 3 and not (2 > 5)) show?
难度 1/5 · 今日首次完成可获 100 金币及少量额外奖励
3 >= 3 is(是) True; 2 > 5 is(是) False, so not (2 > 5) is(是) True. Both sides are true, so and gives True.
if 和 else:二选一的路径
if condition:仅在条件为True时执行缩进的代码块。条件为False时,执行else:代码块。两者中恰好有一个会执行。- 缩进决定了代码块的范围。位于
if下方的缩进行属于该代码块;回到左边缘的第一行无论之前发生了什么都会执行。
if total >= 50:
fee = 0
else:
fee = 5
print("Delivery:", fee) # always runs
A line that is not indented, written straight after an if block, runs only when the condition is True.
难度 1/5 · 今日首次完成可获 100 金币及少量额外奖励
Only indented lines belong to the if. The first line back at the left edge is outside the block, so it runs either way.
elif:第一个为真的分支获胜
- 带有
if … elif … else的选择结构从上到下依次测试条件,仅执行第一个为True的条件。其余条件即使也为真也会被跳过。 else捕获所有剩余情况,因此完整的条件链始终只会执行其中一条路径。

A shop uses if total >= 50: fee = 0, then elif total >= 20: fee = 3, then else: fee = 5. What is fee when total is exactly 20?
难度 2/5 · 今日首次完成可获 140 金币及少量额外奖励
20 >= 50 is(是) False, so the chain moves on; 20 >= 20 is(是) True, so fee = 3 runs and the else is skipped. A boundary value is exactly the case worth testing.
利用依次向下判断的结果
- 只有当上方所有测试都失败时才会到达
elif。因此elif score >= 70不需要and score < 80:能够到达该行本身已证明分数低于80。 - 编写额外的测试会让代码更长,而且每多写一次,就在边界处多了一个出错的地方。
if score >= 80:
band = "A"
# here score < 80 is already known
elif score >= 70:
band = "B"
elif score >= 60:
band = "C"
else:
band = "F"
哪个分支运行?
Drag the score and watch the chain test each condition from the top. Only the first true branch runs; at 79 the test score >= 80 fails and score >= 70 wins.
In the band chain, why does elif score >= 70: not need and score < 80?
难度 1/5 · 今日首次完成可获 100 金币及少量额外奖励
每个 elif inherits the failure of every test above it. A score of 80 or more has already been caught by the first branch.
将较窄的规则放在前面
- 当两条规则都可能为真时,先写出的那条决定结果。应将必须优先匹配的规则(通常是较窄的那条)置于较宽规则的上方。
- 从每条路径各选一个输入进行测试,并选一个同时匹配两条规则的输入。这种重叠情况正是顺序错误隐藏之处。
- 儿童和超过65岁的人付£5,学生付£7,其他人付£10。
- 年龄优先:先
if age < 12 or age >= 65:,再elif student:,最后else:。一名70岁的学生支付**£5**。 - 学生优先:同一个人匹配
if student:,支付**£7**。用一名20岁的学生(£7)和一名30岁的人(£10)进行测试时,两个程序都能通过。只有重叠情况才能显示出差异。
Put the lines in order so that a 70-year-old student pays £5 and a 20-year-old student pays £7.
难度 3/5 · 今日首次完成可获 200 金币及少量额外奖励
The age rule must win the overlap case, so it is tested first. A 20-year-old student fails the age test and reaches elif student:.
谨慎组合条件
- Python允许链式比较:
0 <= mark <= 100的意思是0 <= mark and mark <= 100。 and一旦确定答案就会停止。n != 0 and total / n > 5永远不会除以零,因为当n为0时,左侧已经是False。
Let x = 15. Which conditions are truthy (would be treated as true in an if statement)? Select all that apply.
难度 2/5 · 今日首次完成可获 140 金币及少量额外奖励
The chain holds, and $15$ is a multiple of 5. not x > 10 is(是) False. The last one is the trap: it means (x == 10) or 20, and 20 counts as true, so it is true for every x.
例题解析:电影院的测试清单
- 写出能发现老年人票价错误及任何边界错误的最小测试集。
| 测试及原因 | 预期结果 |
|---|---|
30岁,非学生:else路径 |
£10 |
| 20岁,学生:学生路径 | £7 |
| 8岁:儿童路径 | £5 |
| 70岁,学生:重叠情况 | £5 |
| 11岁和12岁,均非学生:儿童票的边界 | 分别为£5和£10 |
| 64岁和65岁,均非学生:老年人票的边界 | 分别为£10和£5 |
- 八个输入,每个都有其测试理由。重叠情况所在的行能发现顺序错误;边界所在的行能发现应写
<=却写成<的错误。
A program has three separate statements: if score >= 60: print("C"), if score >= 70: print("B"), if score >= 80: print("A"). What does it print for a score of 85?
难度 1/5 · 今日首次完成可获 100 金币及少量额外奖励
Separate if statements are each tested, so all three run. An if … elif chain with the highest band first would print only A.
The cinema code passes tests for a 30-year-old, a 20-year-old student and an 8-year-old. Which extra test would reveal that the student rule was put first?
难度 1/5 · 今日首次完成可获 100 金币及少量额外奖励
Only a customer who matches two rules shows which rule wins. A 70-year-old student should pay £5; with the student rule first, they pay £7.
容易丢掉的分
- 条件中的
=。if x = 5:是语法错误;比较需要使用==。 - **
x == 1 or 2。**这意味着(x == 1) or 2,而2被视为真,因此测试始终为真。应写成x == 1 or x == 2或x in (1, 2)。 - **本意是使用
elif,却使用了多个独立的if。**三个独立的if语句都可能执行;而一个elif链只执行其中一个分支。 - **边界。**应使用
>还是>=?请测试确切的边界值,例如分数恰好为70。
你掌握了
- 条件是一个
bool表达式;可以用比较运算以及and、or和not来构建它。 if … elif … else从上到下依次测试,仅执行第一个为真的分支;else处理剩余情况。- 到达每个
elif时,其上方的测试都已经失败。顺序是设计的一部分:将必须优先匹配的规则放在前面,并测试重叠和边界情况。
| 顾客 | 先测试年龄 | 先测试学生身份 |
|---|---|---|
| 30岁的人 | £10 | £10 |
| 20岁的学生 | £7 | £7 |
| 70岁的学生 | £5:正确 | £7:错误 |
出了什么问题?只有网站团队能看到这些信息。