大家好,我是正在实战各种AI项目的程序员晚枫。
一个真实的场景 去年有个读者问我:"晚枫老师,我写了个计算折扣的程序,结果经常算错几分钱,老板说财务对不上账,怎么办?"
我看了一眼他的代码:
1 2 3 4 5 price = 147.5 discount = 0.8 final_price = price * discount print (final_price)
看起来没问题对吧?但如果是这样呢:
1 2 3 price = 147.7 final_price = price * 0.8
这是浮点数精度问题,很多新手都会踩坑!
上篇我们学了数据类型——知道怎么存放数据了。这篇来学怎么运算数据 ,以及运算中的那些坑。
学完这篇,你的程序就能做加减乘除、比大小、做判断,真正"动起来"了。
算术运算符:数学运算 Python做数学运算,和计算器一样简单——但比计算器强大得多。
先来算一笔账 想象你和朋友吃完饭要AA,总价147元,3个人分:
1 2 3 4 5 6 7 8 9 10 11 12 13 total = 147 people = 3 print (total / people) print (total // people) print (total % people) total = 148 print (total / people) print (total // people) print (total % people)
7种算术运算符一览 1 2 3 4 5 6 7 8 9 a, b = 10 , 3 print (a + b) print (a - b) print (a * b) print (a / b) print (a // b) print (a % b) print (a ** b)
运行结果:
1 2 3 4 5 6 7 13 7 30 3.3333333333333335 3 1 1000
深入理解除法 Python有两种除法,一定要分清:
1 2 3 4 5 6 7 8 9 10 11 12 print (10 / 3 ) print (9 / 3 ) print (10 / 2 ) print (10 // 3 ) print (-10 // 3 )
记住: // 是向下取整(floor division),不是截断。
负数取余的规则 1 2 3 4 5 print (10 % 3 ) print (-10 % 3 ) print (10 % -3 )
生活中用得上的技巧 判断奇偶数:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 age = 25 if age % 2 == 0 : print ("偶数" ) else : print ("奇数" ) if age & 1 == 0 : print ("偶数" ) else : print ("奇数" )
取数字的各个位:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 num = 12345 print (num % 10 ) print (num // 10 % 10 ) print (num // 100 % 10 ) print (num % 100 ) print (num // 100 )
翻转数字:
1 2 3 4 5 6 7 8 9 num = 12345 reversed_num = 0 while num > 0 : digit = num % 10 reversed_num = reversed_num * 10 + digit num = num // 10 print (reversed_num)
四舍五入:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 print (round (3.4 )) print (round (3.5 )) print (round (3.6 )) def my_round (num ): return int (num + 0.5 ) print (my_round(3.4 )) print (my_round(3.5 )) print (round (3.14159 , 2 )) print (round (3.14159 , 3 ))
货币计算(避免浮点数精度问题):
1 2 3 4 5 6 7 8 9 10 11 12 13 price = 0.1 + 0.2 print (price) from decimal import Decimal, ROUND_HALF_UPprice = Decimal('0.1' ) + Decimal('0.2' ) print (price) price_fen = 10 + 20 print (price_fen / 100 )
比较运算符:比大小 比较运算符返回的是布尔值(True 或 False),是条件判断的基础。
6种比较运算符 1 2 3 4 5 6 7 8 score = 85 print (score > 60 ) print (score >= 60 ) print (score < 90 ) print (score <= 90 ) print (score == 85 ) print (score != 100 )
链式比较:Python的优雅写法 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 age = 25 result = age >= 18 and age <= 60 print (result) result = 18 <= age <= 60 print (result) score = 75 print (60 <= score < 80 ) print (0 <= score <= 100 )
比较不同类型 1 2 3 4 5 6 7 8 9 10 11 12 13 14 print (1 < 2.5 ) print (1.0 == 1 ) print ("apple" < "banana" ) print ("Apple" < "apple" ) print ("abc" < "abd" ) print ("ab" < "abc" )
浮点数比较的坑 1 2 3 4 5 6 7 8 9 10 11 12 a = 0.1 + 0.2 b = 0.3 print (a == b) tolerance = 1e-9 print (abs (a - b) < tolerance) import mathprint (math.isclose(a, b))
赋值运算符:边算边存 赋值运算符是把计算结果存回变量,简化代码。
复合赋值运算符 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 x = 10 x += 5 print (x) x -= 3 print (x) x *= 2 print (x) x //= 5 print (x) x **= 2 print (x) x %= 3 print (x)
实际应用场景 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 count = 0 count += 1 count += 1 print (count) total = 0 prices = [10 , 20 , 30 , 40 ] for price in prices: total += price print (total) product = 1 for i in range (1 , 6 ): product *= i print (product)
海象运算符(Python 3.8+) 1 2 3 4 5 6 7 8 9 10 11 12 text = input ("请输入: " ) if len (text) > 5 : print (f"输入了{len (text)} 个字符" ) if (n := len (input ("请输入: " ))) > 5 : print (f"输入了{n} 个字符" )
逻辑运算符:组合判断 and(且)、or(或)、not(非)用来组合多个条件。
and:两个都要满足 1 2 3 4 5 6 7 8 9 10 11 age = 20 balance = 150 can_vip = (age >= 18 ) and (balance >= 100 ) print (can_vip) age = 16 can_vip = (age >= 18 ) and (balance >= 100 ) print (can_vip)
or:满足一个就行 1 2 3 4 5 6 7 8 9 10 11 is_vip = False balance = 600 can_discount = is_vip or (balance >= 500 ) print (can_discount) is_vip = False balance = 200 can_discount = is_vip or (balance >= 500 ) print (can_discount)
not:取反 1 2 3 4 5 6 7 8 9 10 11 is_locked = True print (not is_locked) is_logged_in = False if not is_logged_in: print ("请先登录" ) name = "" if not name: print ("姓名不能为空" )
真值表 A B A and B A or B not A True True True True False True False False True False False True False True True False False False False True
短路求值:Python很聪明 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 result = False and print ("这里不会执行" ) print (result) result = True or print ("这里也不会执行" ) print (result) user = None if user and user.name: print (user.name) else : print ("用户不存在" )
为什么叫短路? Python在and的左边已经知道结果为False,或者or的左边已经知道结果为True时,就不再看后面的代码了——因为后面再怎么看,也不会改变最终结果。这能省时间,有时候还能避免报错 。
逻辑运算返回值 1 2 3 4 5 6 7 8 9 10 11 12 13 14 print (3 and 5 ) print (0 and 5 ) print (3 and 0 ) print (0 and "" ) print (3 or 5 ) print (0 or 5 ) print (0 or "" ) name = input ("请输入姓名: " ) or "匿名用户" print (name)
成员运算符:在一堆东西里找 判断某个元素是否在一组数据中。
in 和 not in 1 2 3 4 5 fruits = ["苹果" , "香蕉" , "橙子" ] print ("苹果" in fruits) print ("葡萄" in fruits) print ("葡萄" not in fruits)
不同类型的应用 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 print ("a" in "apple" ) print ("app" in "apple" ) print ("x" not in "apple" ) numbers = [1 , 2 , 3 , 4 , 5 ] print (3 in numbers) print (6 in numbers) coordinates = (0 , 0 ) print (0 in coordinates) unique_numbers = {1 , 2 , 3 , 4 , 5 } print (3 in unique_numbers) person = {"name" : "张三" , "age" : 25 } print ("name" in person) print ("张三" in person) print ("张三" in person.values())
性能对比 1 2 3 4 5 6 7 8 9 10 11 12 13 import timelarge_list = list (range (1000000 )) start = time.time() print (999999 in large_list)print (f"列表查找: {time.time() - start:.6 f} 秒" )large_set = set (range (1000000 )) start = time.time() print (999999 in large_set)print (f"集合查找: {time.time() - start:.6 f} 秒" )
结论: 频繁查找用集合,速度快几个数量级!
身份运算符:是不是同一个东西 is判断的是两个变量是不是同一个对象 (内存地址相同),==判断的是内容是否相同 。
is vs == 1 2 3 4 5 6 7 a = [1 , 2 , 3 ] b = a c = [1 , 2 , 3 ] print (a is b) print (a is c) print (a == c)
比喻理解 is:这两个人是不是同一个人 (双胞胎也不行,是本人)==:这两个人长得像不像 None的判断 1 2 3 4 5 6 7 8 x = None if x is None : print ("x是None" ) if x == None : print ("x是None" )
小整数缓存 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 a = 256 b = 256 print (a is b) a = 257 b = 257 print (a is b) a = "hello" b = "hello" print (a is b) a = "hello world!" b = "hello world!" print (a is b)
最佳实践 1 2 3 4 5 6 7 8 9 10 11 if x is None : pass if a == b: pass if a is 5 : pass
位运算符:底层操作 位运算直接对二进制位操作,速度快但可读性差。
位运算符一览 1 2 3 4 5 6 7 8 a, b = 60 , 13 print (a & b) print (a | b) print (a ^ b) print (~a) print (a << 2 ) print (a >> 2 )
实际应用 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 num = 7 print (num & 1 ) num = 8 print (num & 1 ) a, b = 10 , 20 a = a ^ b b = a ^ b a = a ^ b print (a, b) a, b = 10 , 20 a, b = b, a print (a, b) READ = 1 WRITE = 2 EXECUTE = 4 permission = READ | WRITE print (permission & READ) print (permission & EXECUTE) num = 10 print (num << 1 ) print (num >> 1 )
运算符优先级:先算谁? 数学里先乘除后加减,Python也一样:
优先级(高→低) 运算符 1 () 括号2 ** 幂3 +x, -x, ~x 正负号、按位取反4 * / // % 乘除取余5 + - 加减6 << >> 移位7 & 按位与8 ^ 按位异或9 ` 10 > < >= <= == != 比较11 is, is not, in, not in 身份和成员12 not 非13 and 且14 or 或
经典陷阱 1 2 3 4 5 6 7 8 9 print (2 ** 3 ** 2 ) print (True == False or True ) print (a is b == c)
最佳实践:用括号 1 2 3 4 5 6 7 8 9 10 result = 2 + 3 * 4 print (result) result = (2 + 3 ) * 4 print (result) result = ((a + b) * c - d) / e
黄金法则: 不确定优先级时,用括号明确意图。
避坑指南:常见错误 错误1:混淆 = 和 == 1 2 3 4 5 6 7 if x = 5 : pass if x == 5 : pass
错误2:浮点数精度 1 2 3 4 5 6 7 8 9 a = 0.1 + 0.2 if a == 0.3 : print ("相等" ) import mathif math.isclose(a, 0.3 ): print ("相等" )
错误3:链式赋值陷阱 1 2 3 4 5 6 7 8 9 10 a = b = [] a.append(1 ) print (b) a = [] b = [] a.append(1 ) print (b)
错误4:运算顺序错误 1 2 3 4 5 6 result = 2 ** 3 ** 2 result = 2 ** (3 ** 2 ) result = (2 ** 3 ) ** 2
错误5:整数除法方向 实战案例:智能评分系统 用运算符写一个成绩评级程序:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 def grade_score (score ): """根据分数返回等级""" if score >= 90 : return "A(优秀)" elif score >= 80 : return "B(良好)" elif score >= 70 : return "C(中等)" elif score >= 60 : return "D(及格)" else : return "F(不及格)" scores = [95 , 82 , 73 , 61 , 45 ] print ("=" * 20 )print ("考试成绩评级" )print ("=" * 20 )for s in scores: result = "及格" if s >= 60 else "不及格" print (f"分数:{s} → 等级:{grade_score(s)} 【{result} 】" ) print ("=" * 20 )
运行结果:
1 2 3 4 5 6 7 8 9 ==================== 考试成绩评级 ==================== 分数:95 → 等级:A(优秀) 【及格】 分数:82 → 等级:B(良好) 【及格】 分数:73 → 等级:C(中等) 【及格】 分数:61 → 等级:D(及格) 【及格】 分数:45 → 等级:F(不及格) 【不及格】 ====================
实战案例:购物车计算 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 def calculate_total (items, discount_rate=0 , member_level="普通" ): """计算购物车总价""" subtotal = sum (item['price' ] * item['quantity' ] for item in items) member_discount = { "普通" : 1.0 , "银卡" : 0.95 , "金卡" : 0.9 , "钻石" : 0.85 } discount = max (discount_rate, 1 - member_discount.get(member_level, 1.0 )) final_price = subtotal * (1 - discount) return { "subtotal" : subtotal, "discount_rate" : discount * 100 , "final_price" : round (final_price, 2 ) } cart = [ {"name" : "苹果" , "price" : 5.5 , "quantity" : 3 }, {"name" : "香蕉" , "price" : 3.0 , "quantity" : 5 }, {"name" : "橙子" , "price" : 4.5 , "quantity" : 2 } ] result = calculate_total(cart, discount_rate=0.1 , member_level="金卡" ) print (f"商品总价:{result['subtotal' ]} 元" )print (f"优惠折扣:{result['discount_rate' ]} %" )print (f"实付金额:{result['final_price' ]} 元" )
实战案例:时间计算器 1 2 3 4 5 6 7 8 9 10 11 12 13 def calculate_time (seconds ): """将秒数转换为时分秒""" hours = seconds // 3600 minutes = (seconds % 3600 ) // 60 secs = seconds % 60 return f"{hours} 小时{minutes} 分钟{secs} 秒" print (calculate_time(3661 )) print (calculate_time(7325 )) print (calculate_time(86400 ))
📚 推荐:Python 零基础实战营 系统学习Python,推荐这个免费入门课程 👇
特点 说明 🎯 专为0基础设计 门槛低,上手快 📹 配套视频讲解 配合文章学习效果更好 💬 专属答疑群 遇到问题有人带 🎁 实体书赠送 优秀学员送《Python编程从入门到实践》
👉 点击免费领取 Python 零基础实战营
本讲小结 运算符 作用 例子 + - * / // % **算术运算 10 / 3 = 3.33> < >= <= == !=比较大小 5 > 3 = Trueand or not逻辑组合 True and False = Falsein / not in成员判断 "a" in "abc" = Trueis / is not身份判断 比较是否同一对象 += -= *= /=赋值运算 x += 1(x加1)`& ^ ~ << >>` 位运算
下节预告 学会了运算,下一篇来学条件判断(if/else) ——让程序学会做选择。
你将学会:
if/elif/else的完整用法 嵌套条件判断 三元表达式 match-case新模式(Python 3.10+) 👉 继续阅读:Python条件判断
课程导航 上一篇: Python零基础入门:写下你的第一行代码
下一篇: Python条件判断-if-else完全指南
相关阅读 PS:运算符是编程的"算盘",多动手算几个生活中的例子,比死记硬背有用得多。记住:代码是写给人看的,顺便给机器运行。
2026-04-23 更新 by 程序员晚枫
🎓 AI 编程实战课程 想系统学习 AI 编程?程序员晚枫的 AI 编程实战课 帮你从零上手!