Python支持一种独特的语法特性:条件表达式可以连写。这种链式比较(Chained Comparisons)可以让代码更加简洁和易读。本文将详细介绍Python中条件表达式连写的用法。

一、链式比较的基本用法

1. 数学风格比较

1
2
3
4
5
6
7
8
9
# 传统写法
x = 5
if x > 0 and x < 10:
print("x在0到10之间")

# Python连写写法
x = 5
if 0 < x < 10:
print("x在0到10之间")

2. 更多示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 判断是否在某个范围内
age = 25
if 18 <= age <= 65:
print("工作年龄") # 输出:工作年龄

# 链式不等式
x = 0.5
if 0 < x < 1:
print("x是0到1之间的分数") # 输出:x是0到1之间的分数

# 多个比较
a, b, c = 3, 5, 7
if a < b < c:
print("a < b < c 成立") # 输出:a < b < c 成立

二、链式比较的原理

1. 等价的展开形式

1
2
3
4
5
6
7
# 链式比较
if 0 < x < 10:
print("x在0到10之间")

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

2. 多个比较链

1
2
3
4
5
6
7
# 三个比较
if a < b < c < d:
print("a < b < c < d")

# 等价于
if a < b and b < c and c < d:
print("a < b < c < d")

3. 不同比较运算符

1
2
3
4
5
6
7
8
9
x = 5
y = 10

# 混合比较运算符
if 0 < x <= 10:
print("0 < x <= 10 成立") # 输出:0 < x <= 10 成立

if 0 < x < y > 3:
print("0 < x < y > 3 成立") # 输出:0 < x < y > 3 成立

三、链式比较的实际应用

1. 范围检查

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 检查数字是否在有效范围内
def validate_score(score):
if 0 <= score <= 100:
return True
return False

print(validate_score(85)) # True
print(validate_score(-5)) # False
print(validate_score(105)) # False

# 检查字符是否在字母范围内
def is_lowercase_letter(c):
if 'a' <= c <= 'z':
return True
return False

print(is_lowercase_letter('g')) # True
print(is_lowercase_letter('A')) # False

2. 边界条件检查

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 边界检查
def classify_age(age):
if 0 <= age < 18:
return "未成年"
elif 18 <= age < 65:
return "工作年龄"
elif 65 <= age <= 120:
return "退休年龄"
else:
return "无效年龄"

# 测试
ages = [-5, 0, 17, 18, 64, 65, 120, 150]
for age in ages:
print(f"age={age}: {classify_age(age)}")

3. 坐标范围检查

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 检查点是否在矩形范围内
def is_in_rectangle(x, y, x1, y1, x2, y2):
"""检查点(x,y)是否在矩形(x1,y1)到(x2,y2)内"""
if x1 <= x <= x2 and y1 <= y <= y2:
return True
return False

# 使用链式比较
def is_in_rectangle_chained(x, y, x1, y1, x2, y2):
"""使用链式比较的版本"""
if x1 <= x <= x2 and y1 <= y <= y2:
return True
return False

print(is_in_rectangle_chained(5, 5, 0, 0, 10, 10)) # True
print(is_in_rectangle_chained(15, 5, 0, 0, 10, 10)) # False

四、链式比较与逻辑运算符的对比

1. 代码简洁性

1
2
3
4
5
6
7
8
9
10
11
12
# 使用逻辑运算符
x = 5
if x > 0 and x < 10 and x != 7:
print("通过")

# 使用链式比较
if 0 < x < 10 != 7: # 这个不等同于上面的表达式
print("通过")

# 正确的链式比较
if 0 < x < 10 and x != 7:
print("通过")

2. 可读性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 检查三个变量是否都大于0
a, b, c = 1, 2, 3

# 链式比较更易读
if a > 0 and b > 0 and c > 0:
print("都大于0")

# 更简洁的写法
if a > 0 and b > 0 and c > 0: # 可以,但有点冗长
print("都大于0")

# 最佳写法
if min(a, b, c) > 0:
print("都大于0")

五、综合示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
链式比较综合示例
"""

def check_triangle(a, b, c):
"""判断是否能构成三角形"""
if a > 0 and b > 0 and c > 0:
if a + b > c and a + c > b and b + c > a:
return "能构成三角形"
return "不能构成三角形"

def check_leap_year(year):
"""判断是否闰年"""
if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0):
return "闰年"
return "平年"

def check_bmi_category(bmi):
"""根据BMI判断体重类别"""
if bmi < 18.5:
return "体重过轻"
elif 18.5 <= bmi < 24:
return "正常"
elif 24 <= bmi < 28:
return "超重"
else:
return "肥胖"

def validate_ip_octet(octet):
"""验证IP段是否合法(0-255)"""
if 0 <= octet <= 255:
return True
return False

def demo():
"""演示"""
# 三角形检查
print("=== 三角形检查 ===")
triangles = [(3, 4, 5), (1, 2, 3), (5, 5, 5)]
for a, b, c in triangles:
print(f"({a}, {b}, {c}): {check_triangle(a, b, c)}")

# 闰年检查
print("\n=== 闰年检查 ===")
years = [2000, 1900, 2024, 2100]
for year in years:
print(f"{year}: {check_leap_year(year)}")

# BMI检查
print("\n=== BMI检查 ===")
bmis = [17, 22, 25, 30]
for bmi in bmis:
print(f"BMI={bmi}: {check_bmi_category(bmi)}")

# IP段检查
print("\n=== IP段检查 ===")
octets = [0, 128, 255, 256]
for octet in octets:
print(f"{octet}: {validate_ip_octet(octet)}")

if __name__ == "__main__":
demo()

六、注意事项

1. 链式比较的顺序

1
2
3
4
5
6
7
# 注意比较的顺序
x = 5

# 0 < x < 10 是正确的
# 10 > x > 0 也是正确的,但不如 0 < x < 10 自然
if 10 > x > 0:
print("正确")

2. 不要混淆逻辑运算符

1
2
3
4
5
6
7
8
9
10
11
# and 和 & 的区别
# and 是逻辑运算符,用于布尔值
# & 是按位运算符,用于整数

x = 5
# 正确:使用链式比较
if 0 < x < 10:
print("正确")

# 不要写成
# if 0 < x and < 10: # 语法错误

3. 性能考虑

1
2
3
4
5
6
7
8
# 链式比较是短路求值
def check(n):
if n > 0 and n < 10 and 100 // n > 5:
return True
return False

# 如果n=0,第一个条件就不通过,后续不会执行
# 如果n=5,所有条件都会检查