Conditionals
引入
9:10
算法与编程
想象一本有一百万个名字的电话簿,你必须找到其中一个。逐个检查,你可能一整天都找不完。有一种方法可以在大约…内找到它
英文讲解 · 可切换中英文字幕
本课内容
| English | 释义 | 拼音 |
|---|---|---|
| conditional/kənˈdɪʃənl/ | 条件语句 | tiáo jiàn yǔ jù |
| block/blɒk/ | 代码块 | dài mǎ kuài |
| if/ɪf/ | 如果 | rú guǒ |
| else/els/ | 否则 | fǒu zé |
| clause/klɔːz/ | 子句 | zǐ jù |
| selection/sɪˈlekʃn/ | 选择 | xuǎn zé |
| iteration/ˌɪtəˈreɪʃn/ | 迭代 | dié dài |
| branch/bræntʃ/ | 分支 | fēn zhī |
| Boolean condition/ˈbuːlɪən kənˈdɪʃn/ | 布尔条件 | bù ěr tiáo jiàn |
选择要做什么
- 条件语句使用条件来决定运行哪个代码块。
- 这让程序能够根据数据选择要做什么。
- 不同的输入可以让程序沿着不同的路径运行。
- 它是每个程序的三个构件之一。
The IF block of a conditional statement runs:
难度 1/5 · 今日首次完成可获 100 金币及少量额外奖励
The condition decides whether the block runs.
In an IF/ELSE, how many branches run each time?
难度 1/5 · 今日首次完成可获 100 金币及少量额外奖励
The condition chooses one branch; the other is skipped.
IF 与 ELSE
- 基本形式是一个 if(如果)语句,常带一个 else(否则)子句(clause):
- IF 条件为真,运行第一个块;
- ELSE(条件为假),运行第二个块。
- 每次恰好运行一个块。

选择(Selection)根据条件在路径之间进行选择
Selection: follow the IF / ELSE branch
Drag the score and watch which branch runs. An IF tests the condition and takes the first block if true, otherwise the ELSE block — only one runs.
Choosing between paths based on a condition is called ______.
难度 1/5 · 今日首次完成可获 100 金币及少量额外奖励
Selection is one of the three building blocks, with sequencing and iteration.
选择
- 这种在路径之间进行选择的能力称为选择(selection)。
- 选择是三个构件之一,另两个是顺序和迭代(iteration)。
- 要理解一个条件语句,追踪对给定输入哪个分支(branch)运行。
- 只有一个分支运行,由条件选定。
IF isMember: price ← price × 0.9. With isMember true and price 100, price becomes:
难度 1/5 · 今日首次完成可获 100 金币及少量额外奖励
The IF branch runs: 100 × 0.9 = 90.
If isMember is false, the IF branch runs and the member discount is applied.
难度 1/5 · 今日首次完成可获 100 金币及少量额外奖励
False. A false condition skips the IF block and runs the ELSE branch, so the price stays 100.
Writing the wrong Boolean condition usually causes:
难度 1/5 · 今日首次完成可获 100 金币及少量额外奖励
A wrong condition sends the program down the wrong branch.
把条件写对
- 确保布尔条件(Boolean condition)正确地捕捉预期的规则。
- 一个错误的条件是逻辑错误的常见来源。
会员折扣。 IF isMember 为真:price ← price × 0.9;ELSE:price 保持不变。isMember 为真、价格 100 时,IF 分支运行 → 价格变成 90。若为假,ELSE 分支运行 → 价格保持 100。
一个条件语句使用条件来决定运行哪个块。一个带 ELSE 的 IF 恰好选两条路径之一——这是选择,三个构件之一。追踪每个输入会运行哪个分支,并确保布尔条件符合你预期的规则。
出了什么问题?只有网站团队能看到这些信息。