人人都能学编程
English 开始学习
课程 2 · Python 入门第 8 课 / 共 14 课免费阅读

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
逐步执行
  1. L270 >= 80?False:跳过。
  2. L470 >= 65?True:运行这个代码块。B
  3. L6后面的检查全部跳过,虽然 70 也 >= 50。

and / or / not

动手试试

改一改 temp 和 raining,运行前先预测输出。

temp = 28
raining = False
print(temp > 25 and not raining)
print(temp < 10 or raining)
逐步执行
  1. L3temp > 25 为 True;not raining 为 True;True and True → True。True
  2. 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")
  1. A
    A
  2. B
    A
    B
  3. C
    B
查看答案

答案:A

第一个为 True 的条件胜出,elif 根本不会被检查。

2. 这段代码会输出什么?

print(5 > 3 and 2 > 4, 5 > 3 or 2 > 4)
  1. A
    False True
  2. B
    True False
  3. C
    True True
查看答案

答案:A

and 要求两个都成立(有一个 False → False);or 只要一个成立(True)。

动手练习

3 道练习,分三层:先预测程序的输出,再按新需求改程序,最后从零写一个。代码在浏览器里运行,提交马上判题。

  1. 预测输出天气用词

    准确写出程序的输出。

  2. 改需求加上 B 等级

    为 65 到 79 分加一个 B 等级。其余不变:80 以上 A,50–64 是 C,50 以下 F。

  3. 从零写闰年

    读入一个年份。是闰年就打印 leap,否则打印 common。规则:能被 4 整除但不能被 100 整除,或者能被 400 整除,就是闰年。

在互动课里练这一课

打开互动课,这些例子都能直接改、直接运行,练习题提交马上判题。免费开始,不用注册。

互动课按顺序解锁:前面的课还没学,会先带你到课程地图。

本课术语

术语中文英文定义
elifelif 分支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.