Selection — IF and CASE · 选择 —— IF 与 CASE
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version. · 此页面需较新浏览器(支持 SharedArrayBuffer)。请升级 Chrome、Edge、Firefox 或 Safari 至最新版本。
English
Making a decision
- Selection means choosing what to do, based on a test.
- An
ifruns its block only when the test is true. - The test gives a Boolean:
TrueorFalse.
中文
做一个决定
- 选择(selection)就是根据一个测试来决定做什么。
if只有当测试为真时才运行它的代码块。- 这个测试会给出一个布尔值:
True或False。
age = 20
if age >= 18:
print("You may vote")
English
else: the other path
elseruns when theiftest is false.- Exactly one of the two blocks runs.
中文
else:另一条路
- 当
if的测试为假时,运行else。 - 两个代码块里恰好运行一个。
mark = 45
if mark >= 50:
print("Pass")
else:
print("Fail")
English
elif: many paths
- Use
elifto test more conditions in order. - Python checks each test top to bottom and stops at the first true one.
中文
elif:多条路
- 用
elif按顺序测试更多条件。 - Python 从上到下逐个检查,在第一个为真的地方停下。
mark = 72
if mark >= 70:
print("A")
elif mark >= 50:
print("B")
else:
print("C")
Explore · 探索
if / elif / else — which runs? · if / elif / else —— 哪个会运行?
Tests run top-down; the first · 第一个 true one runs, the rest are skipped. · 测试从上往下检查;第一个为真的运行,其余跳过。
English
Comparison operators
==means equal to (the exam writes=).!=means not equal to (the exam writes<>).- Also use
<,>,<=,>=.
中文
比较运算符
==表示等于(考试里写作=)。!=表示不等于(考试里写作<>)。- 还有
<、>、<=、>=。
print(5 == 5) # True
print(5 != 3) # True
print(3 <= 2) # False
English
In the exam: IF and CASE
- Pseudocode uses
IF … THEN … ELSE … ENDIF, orCASEfor many fixed choices.
中文
在考试里:IF 与 CASE
- 伪代码用
IF … THEN … ELSE … ENDIF,或用CASE处理多个固定选项。
IF Mark >= 50
THEN
OUTPUT "Pass"
ELSE
OUTPUT "Fail"
ENDIF
English
Common mistakes
- Compare with
==, not=. - Cover every case, including the
else. - Indent the block that belongs to each branch.
中文
常见错误
- 比较用
==,不是=。 - 覆盖每种情况,包括
else。 - 缩进属于每个分支的语句块。
English
Now you try
- Read the input, then choose what to print with
if/elif/else. - Press Check answer to test your code.
中文
现在轮到你
- 读取输入,然后用
if/elif/else选择要打印什么。 - 按检查答案来测试你的代码。
Read a whole number, then print even if it divides by 2 with no remainder, otherwise print odd. For input 4, print even. · 读取一个整数,如果能被 2 整除就打印 even,否则打印 odd。当输入为 4 时,打印 even。
Click Run to see the output here. · 点击“运行”查看此处输出。
Read a mark (0–100). Print A for 70 or more, B for 50–69, and C for anything less. For input 65, print B. · 读取一个分数(0–100)。70 分及以上打印 A,50–69 打印 B,更低打印 C。当输入为 65 时,打印 B。
Click Run to see the output here. · 点击“运行”查看此处输出。
Two numbers a and b are set for you. Use an if to store the larger · 变大 one in biggest. · 两个数 a 和 b 已为你设好。用 if 把较大的那个存进 biggest。
Click Run to see the output here. · 点击“运行”查看此处输出。