Z
ZHANK
流程控制

条件判断 if-else

掌握 if、elif、else 条件语句,理解代码的分支执行

条件判断 if-else

条件判断让程序根据不同的情况执行不同的代码——这是所有逻辑的基础。

学完本章你将掌握: if/elif/else 结构、嵌套条件、三元表达式、match-case 模式匹配。


一、if 基础

python
age = 18

if age >= 18:
    print("成年人")
    print("可以进入")

# 注意:Python 用缩进(4个空格)表示代码块
# 缩进不一致会导致 IndentationError

💡 你知道吗:Python 是少数用缩进来定义代码块的语言。这让代码天然整洁,但也意味着缩进不能随便乱写。


二、if-else

python
score = 75

if score >= 60:
    print("及格!")
    status = "通过"
else:
    print("不及格,继续努力")
    status = "未通过"

print(f"最终状态:{status}")

三、if-elif-else(多分支)

python
score = 85

if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
elif score >= 60:
    grade = "D"
else:
    grade = "F"

print(f"分数 {score} → 等级 {grade}")

# elif 可以有任意多个,else 是可选的
# 一旦某个条件命中,后面的都不会执行

💡 顺序很重要elif 从上到下依次判断。如果把 elif score >= 60 放在 elif score >= 80 前面,60+ 的分数会被第一个命中,永远到不了 80 那个分支。


四、嵌套条件

python
age, has_id = 20, True

if age >= 18:
    if has_id:
        print("验证通过,欢迎进入")
    else:
        print("请出示身份证件")
else:
    print("未成年人禁止进入")

嵌套可以简化:

python
# 上面的嵌套可以写成:
if age >= 18 and has_id:
    print("验证通过")
elif age >= 18 and not has_id:
    print("请出示身份证")
else:
    print("未成年人")

五、三元表达式(一行 if-else)

python
age = 20

# 传统方式
if age >= 18:
    status = "成年人"
else:
    status = "未成年人"

# 三元表达式:一行搞定
status = "成年人" if age >= 18 else "未成年人"

# 更复杂的例子
score = 85
result = "优秀" if score >= 90 else "良好" if score >= 80 else "一般"
print(result)  # 良好

六、组合条件

python
age, score, has_passport = 22, 85, True

# and:所有条件都满足
if age >= 18 and score >= 80:
    print("优秀青年")

# or:满足任一即可
if score >= 90 or has_passport:
    print("符合特殊条件")

# 复杂组合用括号明确意图
if (age >= 18 and score >= 80) or has_passport:
    print("通过")

# not:条件取反
is_banned = False
if not is_banned:
    print("可以访问")

七、match-case(Python 3.10+)

相当于其他语言中的 switch-case:

python
command = "quit"

match command:
    case "start":
        print("开始运行")
    case "pause":
        print("暂停")
    case "stop" | "quit":
        print("停止")
    case _:
        print(f"未知命令: {command}")

更强大的模式匹配:

python
def handle_value(value):
    match value:
        case 0:
            return "零"
        case int(n) if n > 0:
            return f"正整数 {n}"
        case int(n) if n < 0:
            return f"负整数 {n}"
        case str(s):
            return f"字符串: {s}"
        case [first, *rest]:
            return f"列表: 首元素 {first}, 其余 {rest}"
        case _:
            return "未知类型"

print(handle_value(42))        # 正整数 42
print(handle_value("hello"))   # 字符串: hello
print(handle_value([1,2,3]))   # 列表: 首元素 1, 其余 [2, 3]

八、常见陷阱

python
# ❌ 错误:赋值用 = 而不是 ==
age = 20
# if age = 18:    # SyntaxError!应该是 ==

# ❌ 错误:字符串和数字比较
# if "10" > 5:    # TypeError!

# ❌ 错误:空列表不是 None
items = []
# if items == None:     # False!空列表不是 None
if not items:            # ✅ 正确判断空列表
    print("列表为空")

💡 真值测试回顾0 0.0 "" [] {} None 都是 False,其他都是 True。直接 if items: 判断非空列表,简洁又 Pythonic。


小结

  1. if elif else 构成条件判断,缩进定义代码块
  2. and or not 组合条件,括号明确优先级
  3. 三元表达式 = 一行 if-else
  4. Python 3.10+ 支持 match-case 模式匹配
  5. 注意 =(赋值)和 ==(比较)的区别

小练习

  1. 写一个程序,输入年龄,判断是儿童(<12)、青少年(12-17)、成年人(18-59)、还是老年人(60+)
  2. 用三元表达式一行判断一个数是不是偶数
  3. 写一个判断密码强度的条件:长度 >= 8 且包含数字为"强",否则为"弱"

💬 下一章预告:学完条件判断,下一章学习循环语句——用 for 和 while 让代码自动重复执行。