条件语句 #

条件语句用于根据条件执行不同的代码块。

一、基本语法 #

1.1 if语句 #

python
# 基本if语句
age = 18

if age >= 18:
    print("成年人")

# 条件为假时不执行
if age < 18:
    print("未成年人")  # 不会执行

1.2 if-else语句 #

python
age = 16

if age >= 18:
    print("成年人")
else:
    print("未成年人")
# 输出:未成年人

1.3 if-elif-else语句 #

python
score = 85

if score >= 90:
    print("优秀")
elif score >= 80:
    print("良好")
elif score >= 60:
    print("及格")
else:
    print("不及格")
# 输出:良好

二、条件表达式 #

2.1 条件可以是任何表达式 #

python
# 布尔值
flag = True
if flag:
    print("真")

# 数字(非零为真)
count = 5
if count:
    print("有数据")

# 字符串(非空为真)
name = "Tom"
if name:
    print(f"名字是{name}")

# 列表(非空为真)
items = [1, 2, 3]
if items:
    print(f"有{len(items)}个元素")

# None为假
data = None
if not data:
    print("没有数据")

2.2 比较运算 #

python
x, y = 10, 20

if x < y:
    print("x小于y")

if x != y:
    print("x不等于y")

if x <= 10:
    print("x小于等于10")

2.3 逻辑运算 #

python
age = 25
has_license = True

# and:两个条件都满足
if age >= 18 and has_license:
    print("可以开车")

# or:任一条件满足
day = "Saturday"
if day == "Saturday" or day == "Sunday":
    print("周末")

# not:取反
is_banned = False
if not is_banned:
    print("可以进入")

2.4 链式比较 #

python
x = 5

# 链式比较
if 0 < x < 10:
    print("x在0到10之间")

# 等价于
if x > 0 and x < 10:
    print("x在0到10之间")

三、条件表达式(三元运算符) #

3.1 基本语法 #

python
# 语法:value_if_true if condition else value_if_false

age = 20
status = "成年" if age >= 18 else "未成年"
print(status)  # 成年

# 数字判断
x = 10
result = "正数" if x > 0 else "非正数"
print(result)  # 正数

# 绝对值
x = -5
abs_x = x if x >= 0 else -x
print(abs_x)  # 5

3.2 嵌套条件表达式 #

python
score = 75

# 嵌套三元表达式(不推荐过于复杂)
grade = "A" if score >= 90 else "B" if score >= 80 else "C" if score >= 60 else "D"
print(grade)  # C

# 更清晰的写法
if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 60:
    grade = "C"
else:
    grade = "D"

3.3 在表达式中使用 #

python
# 在列表推导式中
numbers = [-2, -1, 0, 1, 2]
abs_numbers = [x if x >= 0 else -x for x in numbers]
print(abs_numbers)  # [2, 1, 0, 1, 2]

# 在函数调用中
def greet(name):
    print(f"Hello, {name or 'Guest'}")

greet("")      # Hello, Guest
greet("Tom")   # Hello, Tom

四、嵌套条件 #

4.1 基本嵌套 #

python
age = 25
has_license = True

if age >= 18:
    print("年龄符合要求")
    if has_license:
        print("可以开车")
    else:
        print("需要考驾照")
else:
    print("年龄不符合要求")

4.2 避免深层嵌套 #

python
# 不推荐:深层嵌套
def check_user(user):
    if user:
        if user.is_active:
            if user.has_permission:
                return True
            else:
                return False
        else:
            return False
    else:
        return False

# 推荐:提前返回
def check_user(user):
    if not user:
        return False
    if not user.is_active:
        return False
    if not user.has_permission:
        return False
    return True

# 或使用链式条件
def check_user(user):
    if user and user.is_active and user.has_permission:
        return True
    return False

五、match-case语句(Python 3.10+) #

5.1 基本用法 #

python
status = 404

match status:
    case 200:
        print("成功")
    case 404:
        print("未找到")
    case 500:
        print("服务器错误")
    case _:  # 默认情况
        print("其他状态")

5.2 模式匹配 #

python
# 匹配多个值
day = "Monday"

match day:
    case "Saturday" | "Sunday":
        print("周末")
    case "Monday" | "Tuesday" | "Wednesday" | "Thursday" | "Friday":
        print("工作日")

# 匹配并解包
point = (1, 2)

match point:
    case (0, 0):
        print("原点")
    case (x, 0):
        print(f"在x轴上,x={x}")
    case (0, y):
        print(f"在y轴上,y={y}")
    case (x, y):
        print(f"坐标:({x}, {y})")

5.3 带守卫的模式 #

python
age = 25

match age:
    case x if x < 18:
        print("未成年")
    case x if x < 60:
        print("成年")
    case _:
        print("老年")

5.4 匹配字典 #

python
def handle_request(request):
    match request:
        case {"method": "GET", "path": path}:
            print(f"GET请求:{path}")
        case {"method": "POST", "path": path, "data": data}:
            print(f"POST请求:{path},数据:{data}")
        case _:
            print("未知请求")

handle_request({"method": "GET", "path": "/users"})

六、pass语句 #

6.1 占位符 #

python
# pass用作占位符
if True:
    pass  # TODO: 稍后实现

# 定义空类
class EmptyClass:
    pass

# 定义空函数
def empty_function():
    pass

6.2 保持语法正确 #

python
# 必须有语句体的地方
def future_feature():
    pass  # 将来实现

if debug:
    pass  # 调试时占位

七、常见模式 #

7.1 范围检查 #

python
age = 25

# 多个范围
if age < 13:
    category = "儿童"
elif age < 18:
    category = "青少年"
elif age < 60:
    category = "成年人"
else:
    category = "老年人"

print(category)  # 成年人

7.2 多条件判断 #

python
role = "admin"

# 使用in
if role in ("admin", "moderator", "editor"):
    print("有管理权限")

# 使用字典
permissions = {
    "admin": "全部权限",
    "moderator": "管理权限",
    "user": "基本权限"
}

permission = permissions.get(role, "无权限")
print(permission)  # 全部权限

7.3 空值检查 #

python
data = None

# 检查None
if data is None:
    print("没有数据")

# 检查空值
name = ""
if not name:
    print("名字为空")

# 区分None和空值
value = None
if value is None:
    print("值为None")
elif value == "":
    print("值为空字符串")

7.4 类型检查 #

python
value = "hello"

# 使用isinstance
if isinstance(value, str):
    print("字符串类型")
elif isinstance(value, int):
    print("整数类型")
elif isinstance(value, (list, tuple)):
    print("序列类型")

# 检查多种类型
if isinstance(value, (int, float)):
    print("数字类型")

八、常见陷阱 #

8.1 忘记冒号 #

python
# 错误
# if True
#     print("True")  # SyntaxError

# 正确
if True:
    print("True")

8.2 缩进错误 #

python
# 错误:缩进不一致
# if True:
#     print("第一行")
#   print("第二行")  # IndentationError

# 正确
if True:
    print("第一行")
    print("第二行")

8.3 条件中的赋值 #

python
# 错误:在条件中使用=而不是==
# if x = 5:  # SyntaxError

# 正确:使用==
if x == 5:
    pass

# Python 3.8+ 海象运算符
if (n := len(items)) > 0:
    print(f"有{n}个元素")

8.4 浮点数比较 #

python
# 浮点数精度问题
a = 0.1 + 0.2
b = 0.3

# 错误方式
# if a == b:  # 可能失败
#     pass

# 正确方式:使用容差
tolerance = 1e-9
if abs(a - b) < tolerance:
    print("相等")

# 或使用decimal
from decimal import Decimal
if Decimal('0.1') + Decimal('0.2') == Decimal('0.3'):
    print("相等")

九、最佳实践 #

9.1 保持条件简单 #

python
# 不推荐
if user and user.profile and user.profile.settings and user.profile.settings.dark_mode:
    print("深色模式")

# 推荐
if user?.profile?.settings?.dark_mode:  # Python不支持这种语法

# Python推荐:提前检查
def is_dark_mode(user):
    if not user or not user.profile:
        return False
    settings = user.profile.settings
    return settings and settings.dark_mode

if is_dark_mode(user):
    print("深色模式")

9.2 使用有意义的变量名 #

python
# 不推荐
if x > 18 and y:
    pass

# 推荐
is_adult = age >= 18
has_license = True
if is_adult and has_license:
    pass

9.3 避免重复条件 #

python
# 不推荐
if role == "admin":
    return True
if role == "moderator":
    return True
if role == "editor":
    return True
return False

# 推荐
if role in ("admin", "moderator", "editor"):
    return True
return False

# 或更简洁
return role in ("admin", "moderator", "editor")

十、总结 #

语句 用途
if 条件为真时执行
if-else 二选一
if-elif-else 多选一
条件 if 表达式 else 条件 三元运算符
match-case 模式匹配(Python 3.10+)
pass 占位符

最佳实践:

  • 保持条件简单明了
  • 避免深层嵌套
  • 使用有意义的变量名
  • 注意浮点数比较
  • 使用 is 检查 None
最后更新:2026-03-16