R / Richie全部文章 ↑

Python · 4 分钟阅读

逻辑判断与条件语句

条件语句控制程序的“分支”。Python 用 if / elif / else + 三个短路运算符
and / or / not 来表达判断逻辑。本章把“真假规则 / 组合条件 / 分支结构 /
常用模式”系统梳理一遍。


1. 真值(Truthy / Falsy)

任何对象都能用在 if 里,Python 会先把它转成 bool:

def is_truthy(x):
    if x:
        print(f"{x!r} 是 truthy")
    else:
        print(f"{x!r} 是 falsy")

常见 falsy 值:

值 说明
False 布尔假
None 空
0 / 0.0 任何数值零
"" 空字符串
[] () {} 任何空容器
set() frozenset() 空集合

自定义类可以通过 __bool__(self) 或 __len__(self) 控制真假。


2. 三个逻辑运算符

运算符 行为
and 左边为 falsy 返回左边,否则返回右边
or 左边为 truthy 返回左边,否则返回右边
not 返回 bool 的相反
a, b = 5, 10

if a > 0 and b > 0:
    print("a 和 b 都是正数")

if a < 0 or b > 0:
    print("a 或 b 是正数")

if not a < 0:
    print("a 不是负数")

Python 的 and / or 不会强制把结果转成 bool——它返回的是“让表达式
决定结果的那个操作数”。这让它们能被巧妙地当成三元写法:

name = user_input or "anonymous"     # 没输入时取默认值
msg  = ok and "一切正常" or "出错了"   # 谨慎用,可读性不好

3. 比较运算符

运算符 含义
== 相等
!= 不等
< <= > >= 大小比较
is / is not 身份比较(同一对象)
in / not in 成员判断
a, b = [1, 2], [1, 2]
print(a == b)     # True    内容相等
print(a is b)     # False   不是同一对象

比较链:Python 允许连写 a < b < c,等价于 a < b and b < c,但 b 只
求值一次
。


4. 条件语句

4.1 基本结构

age = 18

if age >= 60:
    print("老年")
elif age >= 18:
    print("成年")
elif age >= 13:
    print("青少年")
else:
    print("儿童")

4.2 嵌套

age = 20
gender = "female"

if age >= 18:
    if gender == "female":
        print("成年女性")
    else:
        print("成年男性")
else:
    print("未成年人")

嵌套层数过多会难维护。早返回(early return) 通常更好:

def describe(age: int, gender: str) -> str:
    if age < 18:
        return "未成年人"
    return "成年女性" if gender == "female" else "成年男性"

4.3 三元表达式

status = "adult" if age >= 18 else "minor"

适合“一行能写完”的简单分支;多分支请用 if / elif / else。

4.4 match / case(Python 3.10+)

当一个变量要按多种“模式”分发时,match 比 if/elif 更清晰:

def http_status(code: int) -> str:
    match code:
        case 200:
            return "OK"
        case 301 | 302:
            return "Redirect"
        case 404:
            return "Not Found"
        case 500 | 502 | 503:
            return "Server Error"
        case _:
            return "Unknown"

match 还能解构:

match point:
    case (0, 0):
        print("origin")
    case (0, y):
        print(f"y-axis at {y}")
    case (x, 0):
        print(f"x-axis at {x}")
    case (x, y):
        print(f"point ({x}, {y})")

5. 组合条件示例

def can_purchase(age: int, has_id: bool, is_member: bool) -> bool:
    return (age >= 18) and (has_id or is_member)

短路求值:and 遇到 falsy 就停止;or 遇到 truthy 就停止。

users = load_users() or []   # 没结果时取空列表,避免 None

6. 常见模式

6.1 守卫子句(Guard Clause)

def process(data: dict) -> str:
    if not data:
        return "no data"
    if "name" not in data:
        return "missing name"
    return f"hi, {data['name']}"

6.2 字典替代长 if/elif

def operation(op: str, a: int, b: int) -> int:
    return {
        "add":      a + b,
        "sub":      a - b,
        "mul":      a * b,
        "div":      a // b,
    }.get(op, 0)

6.3 列表推导 / 生成器式过滤

nums = [1, 2, 3, 4, 5]
evens = [x for x in nums if x % 2 == 0]

6.4 any / all

nums = [1, 3, 5, 8]
print(any(x % 2 == 0 for x in nums))   # True(至少一个偶数)
print(all(x > 0 for x in nums))        # True(全部正数)

7. 易错点

  • 混淆 = 和 ==:= 是赋值,== 才是比较。在 if x = 1: 里写 =
    是语法错误(直接被拒),不要用 if (x = 1): 这种“绕开”。
  • 链式比较别写错:if 0 < x < 10 ✅;if 0 < x and x < 10 ✅;if 0 < x < 10 == 0 ❌。
  • 可变默认值:if x is not None: 里 is not None 比 != None 更地道。
  • or 取默认值小心“假值”:"" / 0 也会被认为是“空”。如果你的字段
    可能是这些值,请用 if x is None: x = default。
  • is 用在值上:单例(None、True、False)才用 is;其它对象用
    ==。

8. 小结

  • if 后面跟任意表达式,先转 bool(__bool__ / __len__)。
  • and / or 短路求值,返回决定结果的那个操作数。
  • 多分支能 match 就 match,否则 if / elif / else。
  • 嵌套不要超过两层,早返回 + 辅助函数 让结构更平。