Conditionals
| English | Chinese | Pinyin |
|---|---|---|
| conditional | 条件语句 | tiáo jiàn yǔ jù |
| block | 代码块 | dài mǎ kuài |
| if | 如果 | rú guǒ |
| else | 否则 | fǒu zé |
| clause | 子句 | zǐ jù |
| selection | 选择 | xuǎn zé |
| iteration | 迭代 | dié dài |
| branch | 分支 | fēn zhī |
| Boolean condition | 布尔条件 | bù ěr tiáo jiàn |
Choosing what to do
- A conditional 条件语句 runs a block 代码块 of code only when a condition is true.
- This lets a program choose what to do based on data.
- Different inputs can send the program down different paths.
- It is one of the three building blocks of every program.
A conditional statement runs a block of code:
The condition decides whether the block runs.
In an IF/ELSE, how many branches run each time?
The condition chooses one branch; the other is skipped.
IF and ELSE
- The basic form is an if 如果 statement, often with an else 否则 clause 子句:
- IF the condition is true, run the first block;
- ELSE (the condition is false), run the second block.
- Exactly one block runs each time.
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 ______.
Selection is one of the three building blocks, with sequencing and iteration.
Selection
- This ability to choose between paths is called selection 选择.
- Selection is one of three building blocks, with sequencing and iteration 迭代.
- To understand a conditional, trace which branch 分支 runs for a given input.
- Only one branch runs, chosen by the condition.
IF isMember: price ← price × 0.9. With isMember true and price 100, price becomes:
The IF branch runs: 100 × 0.9 = 90.
If isMember is false, the ELSE branch runs and price stays 100.
A false condition runs the ELSE block.
Writing the wrong Boolean condition usually causes:
A wrong condition sends the program down the wrong branch.
Get the condition right
- Make sure the Boolean condition 布尔条件 correctly captures the intended rule.
- A wrong condition is a common source of logic errors.
Member discount. IF isMember is true: price ← price × 0.9; ELSE: price stays the same. With isMember true and price 100, the IF branch runs → price becomes 90. If false, the ELSE branch runs → price stays 100.
A conditional runs a block only when a condition is true. An IF with an ELSE picks exactly one of two paths — this is selection, one of the three building blocks. Trace which branch runs for each input, and make sure the Boolean condition matches the rule you intended.