多条件 and or

18.5 多条件 and or

用 and、or、not 组合条件。

and 表示「并且」都要成立;or 表示「或者」有一个成立即可;not 表示取反。

💡 遇到报错先看最后一行英文提示,再对照「常见错误与正确对比」。

多条件

以下代码含详细中文注释,可直接复制运行。建议对照输出理解每一行的作用。

# ========================================
# 示例:多条件
# 说明:建议复制到 .py 文件运行,或粘贴到 Python 交互模式
# ========================================
score, attendance = 85, True
if score >= 60 and attendance:  # 条件为 True 时执行下方缩进代码
    print('通过')

奖学金条件

成绩>=90 并且 出勤为真,才能获得奖学金。

# ========================================
# 示例:奖学金条件
# 说明:建议复制到 .py 文件运行,或粘贴到 Python 交互模式
# ========================================
score, attendance = 92, True
if score >= 90 and attendance:  # 条件为 True 时执行下方缩进代码
    print('获得奖学金')
else:  # 以上条件都不成立时执行
    print('暂不符合条件')

# or 示例:周末或节假日放假
is_weekend = True  # 赋值:把右边的值存入变量
is_holiday = False  # 赋值:把右边的值存入变量
if is_weekend or is_holiday:  # 条件为 True 时执行下方缩进代码
    print('今天休息')

⚠️ 常见错误与正确对比

❌ 错误写法
if score >= 60 && attendance:
✅ 正确写法
if score >= 60 and attendance:

📌 Python 逻辑与用 and,不是 C/Java 的 &&。