3.Python运算符与表达式:从基础到高效编程实战

55 阅读4分钟

@[toc]

Python运算符与表达式:从基础到高效编程实战

掌握运算符优先级与短路求值,编写简洁高效的逻辑代码


一、运算符分类与核心特性

Python运算符是将数据转化为逻辑输出的“工具包”,按功能分为四类:

类型运算符作用示例
算术运算符+ - * / // % **数学计算10 // 3 → 3(整除)
比较运算符== != > < >= <=关系判断18 <= age < 60(链式比较)
逻辑运算符and or not布尔逻辑组合is_valid and has_permission
赋值运算符= += -= *= /=变量赋值与更新count += 1(等效count=count+1

关键特性解析

  1. 整除与取余陷阱

    print(-10 // 3)  # 输出 -4(向下取整)
    print(10 % 3)    # 输出 1(余数始终非负)
    
  2. 链式比较优化

    # 传统写法:age >= 18 and age < 60
    if 18 <= age < 60:  # 更符合数学直觉
        print("劳动年龄段")
    
  3. 计数器累加

count = 0  
for i in range(10):  
    count += 1   # 等效于 count = count + 1  
print(count)  # 输出:10  
  1. 权限校验(组合not和or)
is_admin = True  
has_license = False  
if is_admin or not has_license:  
    print("允许操作")  # 管理员或无许可均可操作  
  1. 成绩等级判定
score = 85  
if score >= 90:  
    grade = "A"  
elif score >= 80:  # 隐含 score < 90  
    grade = "B"  
elif score >= 70:  
    grade = "C"  
else:  
    grade = "F"  
print(f"成绩等级: {grade}")  # 输出:B  
  1. 时间转换(秒→时分秒)
total_seconds = 7325  
hours = total_seconds // 3600          # 整除获取小时  
remaining_seconds = total_seconds % 3600  # 取模得到剩余秒数  
minutes = remaining_seconds // 60       # 整除获取分钟  
seconds = remaining_seconds % 60        # 取模得到剩余秒  
print(f"{total_seconds}秒 = {hours}小时{minutes}{seconds}秒")  
# 输出:7325秒 = 2小时2分5秒  

二、运算符优先级与短路求值⭐️

1. 优先级规则(从高到低)

result = 2 + 3 * 4 ** 2 // 5 % 3  
# 等价:2 + ((3 * (4**2)) // 5) % 3 → 结果2

速记口诀

号 > 运算 > 乘除 > 加减 > 比较 > not > and > or

2. 短路求值(Short-Circuiting)原理

  • and:遇假即停,返回首个假值
    print(0 and 1/0)  # 输出0,避免除零错误
    
  • or:遇真即停,返回首个真值
    print(3 or 1/0)   # 输出3,跳过异常计算
    

实战意义

# 安全访问嵌套属性
user = None
if user and user.address:  # 避免AttributeError
    print(user.address.city)

三、综合实战案例

案例1:科学计算器(错误处理增强版)

while True:
    try:
        a = float(input("数字1:"))
        op = input("运算符(+, -, *, /, **):")
        b = float(input("数字2:"))
        
        if op == '+': res = a + b
        elif op == '-': res = a - b
        elif op == '*': res = a * b
        elif op == '/': 
            if b == 0: raise ZeroDivisionError
            res = a / b
        elif op == '**': res = a ** b
        else: print("无效运算符"); continue
        
        print(f"{a} {op} {b} = {res:.4f}")
        
    except ZeroDivisionError:
        print("错误:除数不能为0!")  # 处理除零异常
    except ValueError:
        print("错误:请输入有效数字!")
    
    if input("继续?(y/n)").lower() != 'y':
        print("退出计算器")
        break

案例2:智能闰年判断器(逻辑运算符优化)

def is_leap_year(year):
    return (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)

# 测试用例
years = [2000, 2024, 1900, 2025]
for y in years:
    print(f"{y}年: {'闰年' if is_leap_year(y) else '平年'}")

输出

2000年: 闰年
2024年: 闰年
1900年: 平年
2025年: 平年

案例3:权限校验系统(短路求值实战)

def check_permission(user, resource):
    # 短路优化:先检查用户存在性,再验证权限
    return user is not None and user.has_access(resource)

class User:
    def __init__(self, role):
        self.role = role
    def has_access(self, resource):
        return self.role == "admin" or resource in ["public", "profile"]

# 测试
admin = User("admin")
guest = User("guest")
print(check_permission(admin, "dashboard"))  # True
print(check_permission(guest, "profile"))     # True
print(check_permission(None, "public"))       # False(避免None调用方法报错)

四、避坑指南与最佳实践

  1. 优先级陷阱

    # 错误:10 < 5 and 2 > 3 返回True(实际等价于(10<5) and (2>3) → False)
    # 正确:用括号明确意图 (10 < (5 and 2)) > 3
    
  2. 布尔值转换规则

    print(bool("False"))  # True(非空字符串为真)
    print(bool(0.0))      # False(零值为假)
    
  3. 防御性编程技巧

    • 除零检查:if b != 0: res = a/b
    • 类型安全转换:int(float_str) 替代直接 int("3.14")
    • 避免隐式转换:str(True)"True" 而非 1

五、总结与进阶

核心概念关键点应用场景
运算符优先级幂运算 > 乘除 > 加减 > 比较 > 逻辑复杂表达式计算
短路求值and返回首个假值,or返回首个真值条件优化、异常规避
链式比较18 <= age < 60 等效区间判断数据范围验证

学习建议

  1. 每日练习:用不同运算符组合实现数学公式(如圆面积计算)
  2. 调试工具:在PyCharm中使用 Evaluate Expression 观察表达式求值过程
  3. 扩展思考:
    • 如何用位运算符(& | ~)优化权限标志?
    • 理解a += [1]a = a + [1]的内存差异(可变对象原地修改)

“理解短路求值,是写出高效Python代码的关键一步”——避免不必要地计算,让逻辑更优雅

下期预告:4. Python流程控制实战指南:从条件分支到循环优化


本文测试环境:Python 3.10+,所有案例需动手验证以加深理解

更多技术干货欢迎关注微信公众号“科威舟的AI笔记”~

【转载须知】:转载请注明原文出处及作者信息