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之间")
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之间的分数")
a, b, c = 3, 5, 7 if a < b < c: print("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 成立")
if 0 < x < y > 3: print("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)) print(validate_score(-5)) print(validate_score(105))
def is_lowercase_letter(c): if 'a' <= c <= 'z': return True return False
print(is_lowercase_letter('g')) print(is_lowercase_letter('A'))
|
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)) print(is_in_rectangle_chained(15, 5, 0, 0, 10, 10))
|
四、链式比较与逻辑运算符的对比
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
| 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
|
""" 链式比较综合示例 """
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)}")
print("\n=== BMI检查 ===") bmis = [17, 22, 25, 30] for bmi in bmis: print(f"BMI={bmi}: {check_bmi_category(bmi)}")
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
if 10 > x > 0: print("正确")
|
2. 不要混淆逻辑运算符
1 2 3 4 5 6 7 8 9 10 11
|
x = 5
if 0 < x < 10: print("正确")
|
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
|