elif 与 and / or / not · Python 从零开始
如果选择不止两个,或者要同时满足几个条件呢?
课程目录为什么需要它
成绩不只是及格 / 不及格,而是 A、B、C、F。包邮可能要求「订单超过 50 并且在国内」。elif 处理多个选择;and、or、not 用来组合条件。
直觉理解
elif 就是「否则,如果……」。Python 从上到下检查条件,运行第一个为 True 的代码块,然后跳过其余所有的:
if score >= 80:
print("A")
elif score >= 50:
print("C")
else:
print("F")90 分也满足 >= 50,但只会打印 "A":第一个匹配的胜出。所以要把最严格的条件放在前面。
组合条件,也就是逻辑运算符 Logical operator:
a and b:两个都为 True 才是 True。a or b:至少一个为 True 就是 True。not a:把 True 和 False 反过来。
定义
elif 分支
elif (else if) adds another condition to an if statement; the first condition that is True has its block run and the rest are skipped.elif(else if)给 if 语句再加一个条件;第一个为 True 的条件对应的代码块会运行,其余的都跳过。
逻辑运算符 Logical operator
The logical operators and, or and not combine or invert Boolean values.逻辑运算符 and、or、not 用来组合或取反布尔值。
示例
字母等级
动手试试试试 95、70、55 和 20。
score = int(input())
if score >= 80:
print("A")
elif score >= 65:
print("B")
elif score >= 50:
print("C")
else:
print("F")输入(每次 input() 读一行)
70
逐步执行
- L270 >= 80?False:跳过。
- L470 >= 65?True:运行这个代码块。
B - L6后面的检查全部跳过,虽然 70 也 >= 50。
and / or / not
动手试试改一改 temp 和 raining,运行前先预测输出。
temp = 28
raining = False
print(temp > 25 and not raining)
print(temp < 10 or raining)逐步执行
- L3temp > 25 为 True;not raining 为 True;True and True → True。
True - L4temp < 10 为 False;raining 为 False;False or False → False。
False
常见错误
elif 的顺序不对
如果 score >= 50 写在 score >= 80 前面,85 分就会得到较低的等级。最严格的条件放最前面。
`x == 1 or 2`
这不是「x 等于 1 或 2」的意思。两个比较都要写完整:x == 1 or x == 2。
小测验
1. 这段代码会输出什么?
x = 15
if x > 10:
print("A")
elif x > 5:
print("B")
else:
print("C")查看答案
答案:A
第一个为 True 的条件胜出,elif 根本不会被检查。
2. 这段代码会输出什么?
print(5 > 3 and 2 > 4, 5 > 3 or 2 > 4)查看答案
答案:A
and 要求两个都成立(有一个 False → False);or 只要一个成立(True)。
动手练习
3 道练习,分三层:先预测程序的输出,再按新需求改程序,最后从零写一个。代码在浏览器里运行,提交马上判题。
- 预测输出天气用词
准确写出程序的输出。
- 改需求加上 B 等级
为 65 到 79 分加一个 B 等级。其余不变:80 以上 A,50–64 是 C,50 以下 F。
- 从零写闰年
读入一个年份。是闰年就打印
leap,否则打印common。规则:能被 4 整除但不能被 100 整除,或者能被 400 整除,就是闰年。
本课术语
| 术语 | 中文 | 英文定义 |
|---|---|---|
| elif | elif 分支 | An extra condition in an if statement, checked only if the ones above were False. |
| Logical operator | 逻辑运算符 | and, or and not, which combine or invert Boolean values. |
| First match wins | 首个匹配生效 | In an if/elif chain only the first True condition's block runs. |