Skip to main content
Documents
Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Back to homepage

If (条件判断)

官方文档:https://docs.python.org/zh-cn/3.12/reference/compound_stmts.html

🟦 Python if:基础语法

if condition:
    ...
elif condition2:
    ...
else:
    ...

1️⃣ 基础用法示例

x = 10

if x > 5:
    print("大于 5")
elif x == 5:
    print("等于 5")
else:
    print("小于 5")

2️⃣ Python 特有的四种“真假值”判断

Python 中以下值为 False:

  • 0
  • “"(空字符串)
  • [](空列表)
  • {}(空字典)
  • set()
  • None
  • False
  • Decimal(0)
  • 0.0

示例:

if []:
    print("不会执行")

3️⃣ 单行 if

单行写法:

if condition: print("yes")

或者表达式写法(三元表达式):

result = "yes" if x > 1 else "no"

4️⃣ 多条件写法

① and / or

if a > 0 and b < 10:
    ...

② in / not in(常用)

if ext in ["jpg", "png", "gif"]:
    ...

③ 链式比较(Python 独有)

if 0 < x < 10:
    ...

5️⃣ Pythonic 写法(最推荐)

使用“真值判断”

name = input("name:")
if name:
    print("有效名字")

在常量左侧比较(避免拼写错误)

if "admin" == role:  # 推荐
    ...

避免:

if role = "admin":  # 错误

6️⃣ 使用 match-case(Python 3.10+)

比多分支 if-elif 更优雅:

match status:
    case 200:
        print("OK")
    case 404:
        print("Not Found")
    case _:
        print("Unknown")

7️⃣ if 和异常处理配合

if not isinstance(x, int):
    raise TypeError("x must be int")

工程代码常用这种模式。

8️⃣ if 结合列表推导式

过滤:

numbers = [1, 2, 3, 4]
even = [n for n in numbers if n % 2 == 0]

9️⃣ if 结合 any / all(强烈推荐)

在复杂条件判断中非常强大:

if any(ext in filename for ext in [".jpg", ".png"]):
    ...

if all(x > 0 for x in nums):
    ...

🔟 if 的特殊值判断

is 判断对象(None / True / False)

if value is None:
    ...

== 判断内容

if a == b:
    ...

1️⃣1️⃣ if 常见错误

❌ 用 = 代替 ==

❌ 判断空值用 == "”

正确写法:

if not s:
    ...

❌ 不注意缩进

Python 的 if/else 块必须缩进 4 空格。

1️⃣2️⃣ 高级:if 的短路逻辑

x and y
x or y

示例(防止 None):

if user and user.is_active:
    ...

1️⃣3️⃣ if 最佳实践(工程级)

  1. 条件越短越好
  2. 常量放左边比较:if 200 == status
  3. 将复杂条件拆成函数
  4. 尽量避免深层嵌套(早返回模式)

示例:

def process(data):
    if not data:
        return None
    if not validate(data):
        return None
    return save(data)

🏆 速查表(收藏版)

功能 写法
基本分支 if / elif / else
单行 if if x: print(x)
三元表达式 a if cond else b
链式比较 0 < x < 10
多条件 and / or / not
判断集合 in / not in
判空 if not x:
判 None if x is None:
模式匹配 match-case
多条件过滤 any() / all()