刚接触编程时,我常被各种运算符和条件语句绕得头晕。直到有次写自动售货机程序,商品价格比较和找零计算频频出错,才真正明白这些基础概念的重要性。运算符就像数学中的加减乘除,而条件语句则是程序做决策的大脑,两者配合才能让代码"活"起来。
以超市折扣计算为例:当购物满200元打9折,会员再减10元。这个简单的业务逻辑就需要比较运算符(>)、算术运算符(*-)和if语句协同工作。没有它们,程序就只能机械地执行固定流程,无法应对现实世界的复杂场景。
基础的加减乘除(+ - * /)大家都很熟悉,但模运算(%)和幂运算(**)常被忽视。模运算在循环队列、哈希算法中至关重要,比如实现环形缓冲区:
python复制buffer_size = 10
index = (current_index + 1) % buffer_size # 自动循环索引
幂运算在科学计算中很常见,但要注意浮点数精度问题。比较3 ** 2和math.pow(3, 2)会发现,前者返回整数9,后者返回浮点数9.0。
经验:整数除法在Python3中用//,而/会返回浮点结果。这在处理数组索引时要特别注意,避免TypeError。
==和!=看似简单,但实际使用时有很多坑:
abs(a-b) < 1e-9这样的容差判断python复制# 安全浮点数比较
def is_equal(a, b, epsilon=1e-9):
return abs(a - b) < epsilon
and/or的短路特性可以优化性能:
python复制# 避免None引发异常
if user is not None and user.is_active:
...
# 提供默认值
config = user_config or default_config
但在复杂表达式里要小心运算优先级。有个经典bug:
python复制# 错误写法(and优先级高于or)
if x > 0 or y > 0 and z > 0: # 实际相当于 x>0 or (y>0 and z>0)
# 正确写法
if (x > 0 or y > 0) and z > 0:
多层嵌套if不仅难维护,还影响性能。我总结了几条优化原则:
python复制# 优化前
if a > 0:
if b > 0:
if c > 0:
...
# 优化后
if a <= 0:
return
if b <= 0:
return
if c <= 0:
return
简单的条件赋值用三元表达式更简洁:
python复制# 传统写法
if score >= 60:
result = "及格"
else:
result = "不及格"
# 三元表达式
result = "及格" if score >= 60 else "不及格"
但不要滥用,当条件复杂时还是应该用完整if语句。我曾经调试过这样的"聪明"代码:
python复制# 难以理解的嵌套三元
status = "成功" if code == 200 else ("重试" if code in [502,503] else "失败")
if flag == True应该简化为if flagif status == 3不如定义常量STATUS_SUCCESS = 3python复制# 反模式示例
if user.is_active == True: # 冗余比较
if user.credit > 0: # 重复条件
if order.status == 3: # 魔数
...
Python的动态类型很方便,但也会导致意外行为:
python复制print("10" + 5) # TypeError
print(10 + "5") # TypeError
print(10 + 5.0) # 自动转为浮点
比较操作符更复杂:
python复制print(10 == "10") # False
print(10 != "10") # True
print(10 == 10.0) # True
通过魔术方法可以重载运算符:
python复制class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def __eq__(self, other):
return self.x == other.x and self.y == other.y
v1 = Vector(1,2)
v2 = Vector(3,4)
print(v1 + v2) # <__main__.Vector at 0x...>
注意:重载运算符时要保持数学一致性,比如加法应该满足交换律,避免反直觉实现
有些看似等效的操作性能差距很大:
python复制# 测试1:幂运算
%timeit 2 ** 100 # 约85ns
%timeit pow(2, 100) # 约120ns
# 测试2:字符串拼接
%timeit "a" + "b" + "c" # 约50ns
%timeit "".join(["a","b","c"]) # 约150ns(但列表很大时反转)
python复制# 调试示例
debug = True
a, b, c = 1, 0, 1
if debug:
print(f"a={a}, b={b}, c={c}")
# 拆分为中间变量
cond1 = a > 0
cond2 = b > 0 or c > 0
if cond1 and cond2:
...
完善的测试应该覆盖:
python复制def divide(a, b):
if b == 0: # 边界处理
raise ValueError("除数不能为0")
if not isinstance(a, (int, float)) or not isinstance(b, (int, float)):
raise TypeError("只支持数值类型")
return a / b
实现一个促销规则:
python复制def calculate_price(base_price, is_vip, coupon_code=None):
final_price = base_price
if coupon_code:
if validate_coupon(coupon_code):
final_price -= get_coupon_value(coupon_code)
else:
raise InvalidCouponError
else:
if base_price >= 100:
final_price -= 20
if is_vip:
final_price *= 0.9
return max(final_price, 0) # 防止负价格
用条件语句实现简单游戏状态切换:
python复制class GameState:
def __init__(self):
self.state = "MENU"
def update(self, input):
if self.state == "MENU":
if input == "start":
self.state = "PLAYING"
elif input == "quit":
self.state = "EXIT"
elif self.state == "PLAYING":
if input == "pause":
self.state = "PAUSED"
elif input == "die":
self.state = "GAME_OVER"
# 其他状态处理...
组合使用运算符和条件语句进行数据校验:
python复制def validate_user(user):
errors = []
if not (5 <= len(user.username) <= 20):
errors.append("用户名长度需5-20字符")
if not re.match(r'^[\w\.-]+@[\w\.-]+$', user.email):
errors.append("邮箱格式错误")
if user.age < 18 or user.age > 100:
errors.append("年龄需在18-100之间")
return errors if errors else None
(a or b) and c比a or b and c更清晰if not user.is_active比if user.is_active == False更好最后分享一个真实案例:我们系统曾出现一个线上bug,是因为开发写了if a == None or b == None or a == b,本意是想判断a或b为None或者两者相等。但实际上当a为None时,a == b会抛出异常。正确的写法应该是if a is None or b is None or a == b。这个小细节让我深刻理解了is和==的区别以及条件表达式的求值顺序。