记得刚学编程那会儿,最让我头疼的就是各种运算符的优先级问题。明明看起来差不多的表达式,结果却天差地别。后来在调试了无数个bug后才明白,数学运算和逻辑判断是构建程序逻辑的基石,就像盖房子需要稳固的地基一样。
任何程序都离不开对数据的处理和判断。数学运算让我们能够对数值进行各种计算,而逻辑判断则赋予程序"思考"的能力,使其能够根据不同条件执行不同的操作。这两者结合起来,就能实现从简单计算到复杂业务逻辑的各种功能。
加减乘除是最基础的算术运算符,但在编程中它们有些特殊的表现:
python复制# 基本算术运算示例
a = 10 + 5 # 加法 → 15
b = 10 - 5 # 减法 → 5
c = 10 * 5 # 乘法 → 50
d = 10 / 3 # 除法 → 3.333... (浮点数结果)
注意:在不同编程语言中,整数除法的行为可能不同。例如Python 3中
10/3得到浮点数,而Python 2中会截断为整数。
取模运算(%)特别实用,它能得到除法后的余数:
python复制remainder = 10 % 3 # 结果是1,因为10除以3余1
幂运算(**)可以方便地进行指数计算:
python复制square = 5 ** 2 # 25
cube = 2 ** 3 # 8
比较运算符用于比较两个值,返回布尔值(True/False):
python复制x = 10
y = 20
print(x == y) # 等于 → False
print(x != y) # 不等于 → True
print(x > y) # 大于 → False
print(x < y) # 小于 → True
print(x >= 10) # 大于等于 → True
print(y <= 20) # 小于等于 → True
实际经验:在比较浮点数时,由于精度问题,直接使用==可能会出错。建议使用容忍误差的比较方式:
python复制abs(a - b) < 0.00001 # 而不是 a == b
逻辑运算符用于组合多个条件:
and:所有条件都为真时返回真or:任一条件为真时返回真not:对条件取反python复制age = 25
income = 50000
# 组合条件判断
can_apply_loan = (age >= 18) and (income > 30000) # True
is_special_case = (age < 18) or (income > 100000) # False
should_not_approve = not can_apply_loan # False
实用技巧:逻辑运算符有短路特性。
and遇到第一个False就停止,or遇到第一个True就停止。这可以用来安全地检查可能为None的值:python复制value = maybe_none and maybe_none.safe_method()
除了基本的=赋值,还有组合赋值运算符:
python复制count = 5
count += 3 # 等同于 count = count + 3 → 8
count -= 2 # 等同于 count = count - 2 → 6
count *= 4 # 等同于 count = count * 4 → 24
count /= 3 # 等同于 count = count / 3 → 8.0
注意:在某些语言中,像
i++这样的自增运算符与i += 1效果类似,但Python不支持++运算符。
虽然不常用,但位运算符在处理二进制数据时很有用:
python复制a = 0b1100 # 12
b = 0b1010 # 10
print(bin(a & b)) # 位与 → 0b1000 (8)
print(bin(a | b)) # 位或 → 0b1110 (14)
print(bin(a ^ b)) # 位异或 → 0b0110 (6)
print(bin(~a)) # 位取反 → -0b1101 (-13,补码表示)
print(bin(a << 2)) # 左移 → 0b110000 (48)
print(bin(a >> 1)) # 右移 → 0b0110 (6)
运算符优先级决定了表达式中运算的执行顺序。从高到低大致为:
()**+x, -x*, /, %+, -==, !=, >, <, >=, <=notandorpython复制result = 5 + 3 * 2 ** 2 # 等价于 5 + (3 * (2 ** 2)) → 17
当运算符优先级相同时,结合性决定计算顺序:
a + b + c → (a + b) + ca ** b ** c → a ** (b ** c)python复制x = y = z = 0 # 从右向左赋值
result = 2 ** 3 ** 2 # 512 (不是64),因为幂运算是右结合
调试心得:当不确定优先级时,显式使用括号是最安全的做法。这不仅避免错误,也使代码更易读。
最基本的条件控制结构:
python复制temperature = 25
if temperature > 30:
print("天气炎热")
elif temperature > 20:
print("天气温暖") # 这行会执行
else:
print("天气凉爽")
代码风格建议:即使if/elif/else后面只有一行代码,也建议保持缩进和换行,这样更易读和维护。
条件语句可以多层嵌套,但要避免过度嵌套:
python复制age = 25
income = 50000
credit_score = 700
if age >= 18:
if income > 30000:
if credit_score > 650:
print("贷款批准")
else:
print("信用分不足")
else:
print("收入不足")
else:
print("年龄不足")
重构技巧:深层嵌套可以用逻辑运算符扁平化:
python复制if age >= 18 and income > 30000 and credit_score > 650: print("贷款批准")
简洁的条件赋值方式:
python复制# 传统if-else
if age >= 18:
status = "成人"
else:
status = "未成年"
# 三元表达式等价写法
status = "成人" if age >= 18 else "未成年"
注意事项:三元表达式虽然简洁,但过度使用或嵌套会使代码难以理解。建议只在简单条件时使用。
Python中可以直接用值本身作为条件:
python复制name = "Alice"
if name: # 非空字符串为True
print(f"你好,{name}")
count = 0
if not count: # 0等价于False
print("计数为零")
实用技巧:检查空列表/字典/字符串时,直接使用容器本身作为条件比检查长度更Pythonic:
python复制if items: # 比 len(items) > 0 更好 process(items)
当有多个条件需要判断时,有几种组织方式:
python复制# 方法1:使用多个elif
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B" # 这里会匹配
elif score >= 70:
grade = "C"
else:
grade = "D"
# 方法2:使用集合成员检查
valid_colors = {"red", "green", "blue"}
color = "green"
if color in valid_colors:
print("有效颜色")
性能提示:对于大量可能值的检查,使用集合(
{})比列表([])或元组(())更高效,因为集合的成员检查是O(1)时间复杂度。
利用逻辑运算符的短路特性可以实现简洁的条件逻辑:
python复制# 安全访问嵌套字典
config = {"database": {"host": "localhost"}}
# 传统写法
if "database" in config:
if "host" in config["database"]:
host = config["database"]["host"]
else:
host = "default"
else:
host = "default"
# 短路写法
host = config.get("database", {}).get("host", "default")
将条件逻辑封装成函数可以提高可读性和复用性:
python复制def get_discount_level(purchase_amount):
if purchase_amount > 1000:
return "gold"
elif purchase_amount > 500:
return "silver"
else:
return "standard"
discount = 0.1 if get_discount_level(total) == "gold" else 0.05
设计建议:当条件逻辑变得复杂时,考虑使用策略模式或状态模式来替代大量的if-else语句。
python复制# 错误1:混淆=和==
x = 5
if x = 10: # 语法错误,应该是x == 10
print("等于10")
# 错误2:链式比较的错误写法
if 10 < x < 20: # Python支持这种写法,但有些语言不支持
print("x在10和20之间")
# 错误3:浮点数精确比较
a = 0.1 + 0.2
if a == 0.3: # 实际为False,因为浮点精度问题
print("相等")
保持条件简单,复杂逻辑可以提取为函数或变量
python复制# 不推荐
if (user.is_authenticated and user.has_permission('edit') and
not article.is_locked and article.author == user):
edit_article()
# 推荐
can_edit = (user.is_authenticated and
user.has_permission('edit') and
not article.is_locked and
article.author == user)
if can_edit:
edit_article()
避免否定条件的条件语句(除非必要)
python复制# 不推荐
if not user.is_not_active: # 双重否定难理解
send_reminder()
# 推荐
if user.is_active:
send_reminder()
处理所有可能情况,特别是边界条件
python复制# 不安全的写法
if percent > 0.8:
grade = "A"
elif percent > 0.6:
grade = "B"
# 如果percent <= 0.6会怎样?
# 安全的写法
if percent > 0.8:
grade = "A"
elif percent > 0.6:
grade = "B"
else:
grade = "C" # 明确处理所有情况
边界值测试:特别关注条件边界附近的值
python复制def test_score_grade():
assert get_grade(100) == "A"
assert get_grade(90) == "A"
assert get_grade(89) == "B" # 边界测试
assert get_grade(80) == "B"
assert get_grade(70) == "C"
assert get_grade(60) == "D"
assert get_grade(0) == "D"
覆盖率检查:确保所有条件分支都被测试到
使用assert验证条件逻辑
python复制def calculate_discount(total):
assert total >= 0, "总额不能为负"
if total > 1000:
return 0.2
elif total > 500:
return 0.1
else:
return 0
结合运算符和条件语句实现简单计算器:
python复制def calculator():
print("简单计算器")
print("1. 加法")
print("2. 减法")
print("3. 乘法")
print("4. 除法")
choice = input("请选择操作(1/2/3/4): ")
if choice not in ["1", "2", "3", "4"]:
print("无效输入")
return
num1 = float(input("输入第一个数字: "))
num2 = float(input("输入第二个数字: "))
if choice == "1":
print(f"结果: {num1 + num2}")
elif choice == "2":
print(f"结果: {num1 - num2}")
elif choice == "3":
print(f"结果: {num1 * num2}")
elif choice == "4":
if num2 == 0:
print("错误:除数不能为零")
else:
print(f"结果: {num1 / num2}")
多条件组合的成绩评级示例:
python复制def grade_system(score, attendance):
# 输入验证
if not (0 <= score <= 100):
raise ValueError("分数必须在0-100之间")
if not (0 <= attendance <= 1):
raise ValueError("出勤率必须在0-1之间")
# 评级逻辑
if attendance < 0.7:
return "F(出勤不足)"
elif score >= 90:
return "A"
elif score >= 80:
return "B"
elif score >= 70:
return "C"
elif score >= 60:
return "D"
else:
return "F"
使用条件语句检查密码强度:
python复制def check_password_strength(password):
if len(password) < 8:
return "弱:密码太短"
has_upper = any(c.isupper() for c in password)
has_lower = any(c.islower() for c in password)
has_digit = any(c.isdigit() for c in password)
has_special = any(not c.isalnum() for c in password)
strength = 0
if has_upper and has_lower:
strength += 1
if has_digit:
strength += 1
if has_special:
strength += 1
if strength == 0:
return "弱:仅包含一种字符类型"
elif strength == 1:
return "中:包含两种字符类型"
elif strength == 2:
return "强:包含三种字符类型"
else:
return "非常强:包含大小写字母、数字和特殊字符"