Nested Conditionals
| English | Chinese | Pinyin |
|---|---|---|
| nested conditional | 嵌套条件语句 | qiàn tào tiáo jiàn yǔ jù |
| three or more | 三个或更多 | sān gè huò gèng duō |
| outcomes | 结果 | jié guǒ |
| else-if | 否则如果 | fǒu zé rú guǒ |
| execution path | 执行路径 | zhí xíng lù jìng |
| readability | 可读性 | kě dú xìng |
When two paths aren't enough
- Sometimes one decision is not enough.
- A nested conditional 嵌套条件语句 places one conditional inside another.
- This lets a program select among three or more 三个或更多 outcomes 结果, not just two.
- Think grades A, B, C, F — four outcomes from one score.
A nested conditional lets a program:
Nesting adds more branches than a single IF/ELSE.
A nested conditional selects among three or more possible ______.
Each branch leads to a different outcome.
The else-if structure
- A clean way to write this is an else-if 否则如果 structure, testing conditions in sequence:
- IF the first is true, do the first thing;
- ELSE IF the second is true, do the second thing;
- ELSE do the last thing.
An else-if chain for grades
Drag the score and watch which branch runs. An else-if chain tests top to bottom and takes the FIRST condition that is true.
An else-if chain stops testing:
It takes the first true branch and skips the rest.
Order how the program checks the grade conditions.
It tests from the top down and stops at the first true one.
Trace the path
- The program checks conditions from top to bottom.
- It stops at the first one that is true.
- To understand nested conditionals, trace the execution path 执行路径 for given inputs.
- Follow each true-or-false result to see which branch wins.
With the grade chain (≥90 A, ≥80 B, ≥70 C, else F), score 85 gives:
85 ≥ 90 is false; 85 ≥ 80 is true → "B", and testing stops.
Simplifying deeply nested conditionals improves readability and reduces errors.
Fewer, clearer branches are easier to get right.
Keep it readable
- Deeply nested logic can become hard to read.
- Simplify overly complex nesting to improve readability 可读性 and reduce errors.
Score to grade. IF score ≥ 90 → "A"; ELSE IF ≥ 80 → "B"; ELSE IF ≥ 70 → "C"; ELSE → "F". For score 85: 85 ≥ 90 is false, so move on; 85 ≥ 80 is true → grade "B", and testing stops. Order matters — we already know it is below 90.
A nested conditional chooses among three or more outcomes, usually with an else-if chain that tests top to bottom and stops at the first true condition. Trace the execution path to find which branch runs (score 85 → "B"), and keep nesting shallow for readability.