显示页面讨论过去修订反向链接回到顶部 本页面只读。您可以查看源文件,但不能更改它。如果您觉得这是系统错误,请联系管理员。 ====== 第三章:运算符与表达式 ====== ===== 本章目标 ===== 完成本章学习后,你将能够: * 掌握Python所有类型的运算符 * 理解运算符优先级和结合性 * 熟练使用各种表达式 * 掌握海象运算符等Python 3.8+新特性 ===== 算术运算符 ===== ==== 基本算术运算 ==== <code python> a, b = 17, 5 print(a + b) # 加法:22 print(a - b) # 减法:12 print(a * b) # 乘法:85 print(a / b) # 除法:3.4(总是返回float) print(a // b) # 整除:3(向下取整) print(a % b) # 取模:2(余数) print(a ** b) # 幂运算:1419857 </code> ==== 整除(//)的细节 ==== <code python> # 正数 print(7 // 3) # 2 # 负数(向负无穷取整) print(-7 // 3) # -3,不是 -2! print(7 // -3) # -3 # 与int()的区别 print(int(7 / 3)) # 2 print(int(-7 / 3)) # -2(向零取整) print(-7 // 3) # -3(向负无穷取整) </code> ==== 取模(%)的数学原理 ==== <code python> # a % b 的结果总是与b同号(或与0同号) print(7 % 3) # 1 print(-7 % 3) # 2(不是 -1!) print(7 % -3) # -2 print(-7 % -3) # -1 # 应用:判断奇偶 def is_even(n): return n % 2 == 0 # 应用:循环索引 colors = ["red", "green", "blue"] for i in range(10): print(colors[i % len(colors)]) # 循环使用颜色 </code> ===== 比较运算符 ===== <code python> a, b = 10, 20 print(a == b) # 等于:False print(a != b) # 不等于:True print(a > b) # 大于:False print(a < b) # 小于:True print(a >= b) # 大于等于:False print(a <= b) # 小于等于:True </code> ==== 链式比较 ==== Python支持数学风格的链式比较: <code python> x = 15 # 传统写法 if x > 10 and x < 20: print("在范围内") # Pythonic写法 if 10 < x < 20: print("在范围内") # 更复杂的链式 a, b, c = 1, 2, 3 print(a < b < c) # True print(a < b > c) # False(a<b为True,但b>c为False) print(a == b == c) # False </code> ==== is 与 == 的区别 ==== <code python> # == 比较值 print([1, 2, 3] == [1, 2, 3]) # True # is 比较身份(内存地址) print([1, 2, 3] is [1, 2, 3]) # False a = [1, 2, 3] b = a print(a is b) # True # None检查应使用is if x is None: print("x是None") </code> ===== 赋值运算符 ===== ==== 基本赋值 ==== <code python> x = 10 # 简单赋值 a = b = c = 0 # 链式赋值 x, y = 1, 2 # 解包赋值 </code> ==== 复合赋值运算符 ==== <code python> x = 10 x += 5 # x = x + 5,结果为15 x -= 3 # x = x - 3,结果为12 x *= 2 # x = x * 2,结果为24 x /= 4 # x = x / 4,结果为6.0 x //= 2 # x = x // 2,结果为3.0 x %= 2 # x = x % 2,结果为1.0 x **= 3 # x = x ** 3,结果为1.0 </code> ==== 海象运算符(:=)Python 3.8+ ==== **walrus operator** 允许在表达式中进行赋值: <code python> # 传统写法 line = input() while line != "quit": print(f"输入:{line}") line = input() # 使用海象运算符 while (line := input()) != "quit": print(f"输入:{line}") # 在列表推导中使用 values = [1, 2, 3, 4, 5] results = [y for x in values if (y := x * 2) > 4] print(results) # [6, 8, 10] # 在if语句中使用 if (n := len(data)) > 10: print(f"数据过长:{n}个元素") </code> ===== 位运算符 ===== 位运算符直接操作二进制位: <code python> a, b = 5, 3 # 二进制:101 和 011 print(a & b) # 按位与:1(001) print(a | b) # 按位或:7(111) print(a ^ b) # 按位异或:6(110) print(~a) # 按位取反:-6(二进制补码) print(a << 2) # 左移2位:20(10100) print(a >> 1) # 右移1位:2(10) </code> ==== 位运算应用 ==== <code python> # 权限系统 READ = 4 # 100 WRITE = 2 # 010 EXECUTE = 1 # 001 # 设置权限 permission = READ | WRITE # 110 = 6 # 检查权限 if permission & READ: print("有读权限") if permission & EXECUTE: print("有执行权限") # 不会输出 # 切换权限 permission ^= WRITE # 异或切换写权限 # 判断奇偶(比%更快) def is_odd(n): return n & 1 == 1 # 乘以/除以2的幂(比*/更快) print(10 << 1) # 20,等同于10 * 2 print(10 >> 1) # 5,等同于10 // 2 </code> ===== 逻辑运算符 ===== ==== and、or、not ==== <code python> print(True and False) # False print(True or False) # True print(not True) # False </code> ==== 短路求值 ==== Python的逻辑运算符使用**短路求值**: <code python> # and:如果第一个为False,返回第一个值;否则返回第二个值 print(0 and 5) # 0 print(3 and 5) # 5 print("" and "hi") # "" # or:如果第一个为True,返回第一个值;否则返回第二个值 print(3 or 5) # 3 print(0 or 5) # 5 print("" or "hi") # "hi" # 应用:默认值 name = user_input or "Anonymous" # 应用:条件执行 def debug(): print("调试信息") return True is_debug = False is_debug and debug() # 不会调用debug() </code> ==== 真值测试 ==== 以下值在布尔上下文中为**False**: * None * False * 0(任何数字类型的零) * 空字符串 "" * 空列表 [] * 空元组 () * 空字典 {} * 空集合 set() 其他所有值都为**True**。 ===== 成员运算符 ===== ==== in 和 not in ==== <code python> # 字符串 print("a" in "apple") # True print("z" not in "apple") # True # 列表 print(3 in [1, 2, 3]) # True print(4 not in [1, 2, 3]) # True # 字典(检查键) print("name" in {"name": "Alice", "age": 25}) # True print("Alice" in {"name": "Alice"}) # False(检查的是键) # 元组 print((1, 2) in [(1, 2), (3, 4)]) # True </code> ===== 身份运算符 ===== ==== is 和 is not ==== <code python> a = [1, 2, 3] b = [1, 2, 3] c = a print(a is b) # False(不同对象) print(a is c) # True(同一对象) print(a is not b) # True # 小整数缓存 x = 100 y = 100 print(x is y) # True(缓存) z = 1000 w = 1000 print(z is w) # False(可能,取决于实现) # None检查 if value is None: pass </code> ===== 运算符优先级 ===== 从高到低排序: | 优先级 | 运算符 | 描述 | | 1 | () | 括号 | | 2 | ** | 幂运算 | | 3 | +x, -x, ~x | 一元正负、按位取反 | | 4 | *, @, /, //, % | 乘、除、整除、取模 | | 5 | +, - | 加、减 | | 6 | <<, >> | 位移 | | 7 | & | 按位与 | | 8 | ^ | 按位异或 | | 9 | 竖线 | 按位或 | | 10 | ==, !=, >, <, >=, <=, is, in | 比较 | | 11 | not | 逻辑非 | | 12 | and | 逻辑与 | | 13 | or | 逻辑或 | | 14 | if-else | 条件表达式 | | 15 | =, +=, -= 等 | 赋值 | ===== 条件表达式(三元运算符)===== <code python> # 语法:value_if_true if condition else value_if_false age = 20 status = "成年" if age >= 18 else "未成年" print(status) # 成年 # 嵌套(不推荐,可读性差) grade = "A" if score >= 90 else "B" if score >= 80 else "C" # 等价的if语句 if age >= 18: status = "成年" else: status = "未成年" </code> ===== 本章练习 ===== 1. **计算器**:实现支持+、-、*、/、//、%、**的计算器 2. **权限系统**:使用位运算实现文件权限管理系统 3. **闰年判断**:使用条件表达式判断某年是否为闰年 4. **海象运算符练习**:改写一段使用while循环的代码,使用海象运算符简化 5. **优先级测试**:预测并验证以下表达式的结果: - 2 ** 3 ** 2 - 10 - 4 + 2 - not 1 or 0 and 1 or 3 and 4 or 5 and 6 or 7 and 8 and 9 ===== 本章小结 ===== 本章我们学习了: * 各种算术运算符及其特性 * 比较运算符和链式比较 * 赋值运算符,包括海象运算符 * 位运算符及应用 * 逻辑运算符的短路求值 * 成员和身份运算符 * 运算符优先级 * 条件表达式 下一章:[[python_course:chapter04|第四章:条件语句]] 登录 Detach Close 该主题尚不存在 您访问的页面并不存在。如果允许,您可以使用创建该页面按钮来创建它。 python/chapter03.txt 最后更改: 2026/04/09 14:24由 张叶安 登录