If (条件判断)
官方文档:https://docs.python.org/zh-cn/3.12/reference/compound_stmts.html
if condition:
...
elif condition2:
...
else:
...
x = 10
if x > 5:
print("大于 5")
elif x == 5:
print("等于 5")
else:
print("小于 5")
Python 中以下值为 False:
- 0
- “"(空字符串)
- [](空列表)
- {}(空字典)
- set()
- None
- False
- Decimal(0)
- 0.0
示例:
if []:
print("不会执行")
单行写法:
if condition: print("yes")
或者表达式写法(三元表达式):
result = "yes" if x > 1 else "no"
if a > 0 and b < 10:
...
if ext in ["jpg", "png", "gif"]:
...
if 0 < x < 10:
...
使用“真值判断”
name = input("name:")
if name:
print("有效名字")
在常量左侧比较(避免拼写错误)
if "admin" == role: # 推荐
...
避免:
if role = "admin": # 错误
比多分支 if-elif 更优雅:
match status:
case 200:
print("OK")
case 404:
print("Not Found")
case _:
print("Unknown")
if not isinstance(x, int):
raise TypeError("x must be int")
工程代码常用这种模式。
过滤:
numbers = [1, 2, 3, 4]
even = [n for n in numbers if n % 2 == 0]
在复杂条件判断中非常强大:
if any(ext in filename for ext in [".jpg", ".png"]):
...
if all(x > 0 for x in nums):
...
is 判断对象(None / True / False)
if value is None:
...
== 判断内容
if a == b:
...
❌ 用 = 代替 ==
❌ 判断空值用 == "”
正确写法:
if not s:
...
❌ 不注意缩进
Python 的 if/else 块必须缩进 4 空格。
x and y
x or y
示例(防止 None):
if user and user.is_active:
...
- 条件越短越好
- 常量放左边比较:if 200 == status
- 将复杂条件拆成函数
- 尽量避免深层嵌套(早返回模式)
示例:
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() |