8 minutes
运算符与表达式
前面两篇文章我们学习了变量和数据类型,现在你已经能用变量存储各种数据了。但仅仅存储数据是不够的——我们需要对数据进行操作和计算。这就需要用到运算符和表达式。
在 Python 中,表达式是由变量、字面量和运算符组成的可求值代码片段。例如 2 + 3 是一个表达式,它的值是 5。
算术运算符
算术运算符用于执行数学计算,是编程中最基础的操作。
# 基本算术运算
a = 10
b = 3
print(f"a + b = {a + b}") # 13 加法
print(f"a - b = {a - b}") # 7 减法
print(f"a * b = {a * b}") # 30 乘法
print(f"a / b = {a / b}") # 3.3333333333333335 除法(结果总是浮点数)
print(f"a // b = {a // b}") # 3 整除(向下取整)
print(f"a % b = {a % b}") # 1 取余(模运算)
print(f"a ** b = {a ** b}") # 1000 幂运算
整除的细节
整除 // 的结果是"向下取整",对于负数需要特别注意:
# 正数整除
print(7 // 3) # 2
print(8 // 3) # 2
print(9 // 3) # 3
# 负数整除(向下取整)
print(-7 // 3) # -3(-2.333... 向下取整到 -3,不是 -2!)
print(7 // -3) # -3
# 对比:int() 是向零取整
print(int(-7 / 3)) # -2(向零取整)
print(-7 // 3) # -3(向下取整)
取余运算的应用
# 判断奇偶
number = 42
if number % 2 == 0:
print(f"{number} 是偶数")
else:
print(f"{number} 是奇数")
# 数字各位之和
num = 12345
digit_sum = 0
while num > 0:
digit_sum += num % 10
num //= 10
print(f"各位之和: {digit_sum}") # 15
# 循环索引(取模实现循环)
days = ["周一", "周二", "周三", "周四", "周五", "周六", "周日"]
for i in range(14):
print(f"第{i+1}天是{days[i % 7]}")
比较运算符
比较运算符用于比较两个值,返回布尔值(True 或 False):
x, y = 5, 10
print(x == y) # False 等于
print(x != y) # True 不等于
print(x < y) # True 小于
print(x > y) # False 大于
print(x <= y) # True 小于等于
print(x >= y) # False 大于等于
链式比较
Python 支持独特的链式比较语法:
# 其他语言需要这样写
# if (x > 0 && x < 10)
# Python 可以链式比较
x = 5
print(0 < x < 10) # True (等价于 0 < x and x < 10)
print(1 <= x <= 5) # True
print(0 < x < 5 < 10) # True (支持多级链式)
# 实际应用:判断分数区间
score = 85
if 60 <= score < 80:
print("及格")
elif 80 <= score < 90:
print("良好")
elif 90 <= score <= 100:
print("优秀")
字符串比较
# 字符串比较
print("apple" < "banana") # True(按字母顺序)
print("Apple" < "apple") # True(大写字母的编码小于小写)
print("张三" < "李四") # True(按 Unicode 编码比较)
# 实际应用
usernames = ["admin", "Alice", "Bob", "Charlie"]
usernames.sort()
print(usernames) # ['Alice', 'Bob', 'Charlie', 'admin']
逻辑运算符
逻辑运算符用于组合多个条件表达式:
# and(逻辑与):所有条件为 True 才为 True
print(True and True) # True
print(True and False) # False
print(False and False) # False
# or(逻辑或):任一条件为 True 即为 True
print(True or False) # True
print(False or False) # False
# not(逻辑非):取反
print(not True) # False
print(not False) # True
短路求值(Short-Circuit Evaluation)
Python 的逻辑运算符采用短路求值策略——当结果已经确定时,不再继续计算后面的表达式:
# and 短路:第一个为 False 时,不计算第二个
def check_and():
print("check_and 被调用了!")
return True
result = False and check_and()
print(f"结果: {result}") # check_and 没有被调用!
# or 短路:第一个为 True 时,不计算第二个
result = True or check_and()
print(f"结果: {result}") # check_and 没有被调用!
# 实际应用:安全调用
user = None
name = user and user.get("name")
print(name) # None(不会报错)
# 设置默认值
name = input("请输入名字: ") or "匿名用户"
print(f"你好,{name}")
实际应用:条件组合
# 验证用户输入
age = 25
has_id = True
is_vip = False
# 复合条件判断
if age >= 18 and has_id:
print("允许进入")
# 多项条件
if age >= 60 or is_vip:
print("享受优惠")
赋值运算符
除了基本的 = 赋值,Python 还提供复合赋值运算符:
x = 10
x += 3 # x = x + 3 -> 13
print(x)
x -= 5 # x = x - 5 -> 8
print(x)
x *= 2 # x = x * 2 -> 16
print(x)
x /= 4 # x = x / 4 -> 4.0
print(x)
x //= 2 # x = x // 2 -> 2.0
print(x)
x **= 3 # x = x ** 3 -> 8.0
print(x)
y = 17
y %= 5 # y = y % 5 -> 2
print(y)
海象运算符(Python 3.8+)
# 可以在表达式中赋值
if (n := len("Python")) > 3:
print(f"长度是 {n}") # 长度是 6
位运算符
位运算符直接操作整数的二进制位,在底层编程和性能优化中很有用:
a = 0b1100 # 12(二进制)
b = 0b1010 # 10(二进制)
# 位与 &
print(bin(a & b)) # 0b1000(对应位都为 1 才为 1)
print(a & b) # 8
# 位或 |
print(bin(a | b)) # 0b1110(对应位至少一个为 1 即为 1)
print(a | b) # 14
# 异或 ^
print(bin(a ^ b)) # 0b0110(对应位不同才为 1)
print(a ^ b) # 6
# 取反 ~
print(bin(~a)) # -0b1101(所有位取反)
print(~a) # -13
# 左移 <<
print(a << 2) # 48(相当于乘以4)
# 右移 >>
print(a >> 2) # 3(相当于除以4取整)
位运算的实用技巧
# 判断奇偶(比 % 2 更快)
def is_odd(n):
return n & 1 == 1
print(is_odd(5)) # True
print(is_odd(6)) # False
# 判断 2 的幂
def is_power_of_two(n):
return n > 0 and (n & (n - 1)) == 0
print(is_power_of_two(8)) # True
print(is_power_of_two(10)) # False
成员运算符
成员运算符用于检查一个值是否在容器(列表、字符串、元组等)中:
# in 运算符
fruits = ["苹果", "香蕉", "橙子"]
print("苹果" in fruits) # True
print("葡萄" in fruits) # False
# 字符串中的成员检查
text = "Hello, Python!"
print("Python" in text) # True
print("Java" in text) # False
# 实际应用:输入验证
valid_choices = ["yes", "no", "y", "n"]
choice = input("请选择 (yes/no): ").lower()
if choice in valid_choices:
print(f"你选择了 {choice}")
else:
print("无效的选择")
身份运算符
身份运算符用于比较两个对象是否是同一个对象(即内存地址相同):
# is 和 == 的区别
# == 比较值是否相等
# is 比较是否是同一个对象
a = [1, 2, 3]
b = [1, 2, 3]
c = a
print(a == b) # True(值相等)
print(a is b) # False(不同对象)
print(a is c) # True(同一个对象)
# 小整数缓存
x = 256
y = 256
print(x is y) # True(Python 缓存了 -5 到 256 的小整数)
x = 257
y = 257
print(x is y) # False(超出了缓存范围)
# 正确用法:检查 None
value = None
if value is None: # 标准写法
print("空值")
if value is not None:
print("非空")
is 与 == 的对比
| 运算符 | 比较内容 | 典型用途 |
|---|---|---|
is |
对象身份(内存地址) | 检查 None、True、False |
== |
值是否相等 | 比较数值、字符串等数据 |
is not |
与 is 相反 |
if x is not None |
!= |
与 == 相反 |
值不相等时 |
运算符优先级
当一个表达式中有多个运算符时,优先级决定了计算的顺序:
# 优先级从高到低
# 1. () 括号
# 2. ** 幂运算
# 3. +x, -x, ~x 一元运算符
# 4. *, /, //, % 乘除取余
# 5. +, - 加减
# 6. <<, >> 移位
# 7. & 位与
# 8. ^ 位异或
# 9. | 位或
# 10. ==, !=, <, >, <=, >= 比较
# 11. not 逻辑非
# 12. and 逻辑与
# 13. or 逻辑或
# 示例
result = 2 + 3 * 4 ** 2
# 先算 4**2 = 16
# 再算 3 * 16 = 48
# 最后 2 + 48 = 50
print(result) # 50
# 用括号改变优先级
result = (2 + 3) * (4 ** 2)
print(result) # 5 * 16 = 80
# 复杂表达式用括号明确意图
x = True or False and False
print(x) # True(and 优先级高于 or)
完整运算符优先级表
| 优先级 | 运算符 | 说明 |
|---|---|---|
| 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 |
逻辑或 |
运算符汇总表
| 类别 | 运算符 | 示例 | 结果 |
|---|---|---|---|
| 算术 | + |
5 + 3 |
8 |
| 算术 | - |
5 - 3 |
2 |
| 算术 | * |
5 * 3 |
15 |
| 算术 | / |
5 / 3 |
1.666... |
| 算术 | // |
5 // 3 |
1 |
| 算术 | % |
5 % 3 |
2 |
| 算术 | ** |
5 ** 3 |
125 |
| 比较 | ==, !=, <, >, <=, >= |
5 < 3 |
False |
| 逻辑 | and, or, not |
True and False |
False |
| 赋值 | =, +=, -=, … |
x += 1 |
x = x + 1 |
| 成员 | in, not in |
"a" in "abc" |
True |
| 身份 | is, is not |
x is None |
检查身份 |
实践练习:综合计算器
# advanced_calculator.py
print("=" * 40)
print(" Python 高级计算器")
print("=" * 40)
a = float(input("请输入第一个数字: "))
b = float(input("请输入第二个数字: "))
print(f"""
--- 算术运算 ---
{a} + {b} = {a + b}
{a} - {b} = {a - b}
{a} * {b} = {a * b}
{a} / {b} = {a / b}
{a} // {b} = {a // b}
{a} % {b} = {a % b}
{a} ** {b} = {a ** b}
--- 比较运算 ---
{a} == {b}: {a == b}
{a} != {b}: {a != b}
{a} < {b}: {a < b}
{a} > {b}: {a > b}
--- 逻辑运算 ---
(a > 0) and (b > 0): {a > 0 and b > 0}
(a > 0) or (b > 0): {a > 0 or b > 0}
not (a > 0): {not (a > 0)}
""")
# 额外功能:判断数字特性
print("--- 数字特性 ---")
print(f"{a} 是偶数: {a % 2 == 0}")
print(f"{b} 是偶数: {b % 2 == 0}")
print(f"{a} 在 0~100 之间: {0 < a < 100}")
print(f"{b} 在 0~100 之间: {0 < b < 100}")
常见陷阱
1. 浮点数相等比较
# 错误
if 0.1 + 0.2 == 0.3:
print("相等") # 不会执行!
# 正确:使用误差范围
if abs(0.1 + 0.2 - 0.3) < 1e-9:
print("近似相等")
2. is 和 == 混用
# 错误
if value == None: # 虽然可以工作,但不是标准写法
# 正确
if value is None: # 检查 None 必须用 is
3. 逻辑运算符的返回值
# Python 的 and/or 返回的不是布尔值,而是最后一个被求值的操作数
print(0 and 100) # 0(0 是假值,短路返回 0)
print(3 and 100) # 100(3 是真值,继续计算返回 100)
print(0 or 100) # 100(0 是假值,继续计算返回 100)
print(3 or 100) # 3(3 是真值,短路返回 3)
# 利用这个特性设置默认值
name = input("输入名字: ") or "匿名"
小结
在这篇文章中,我们学习了:
- 算术运算符:
+,-,*,/,//,%,** - 比较运算符:
==,!=,<,>,<=,>=和链式比较 - 逻辑运算符:
and,or,not以及短路求值 - 赋值运算符:
=和复合赋值运算符 - 位运算符:
&,|,^,~,<<,>> - 成员运算符:
in,not in - 身份运算符:
is,is not(与==的区别) - 运算符优先级规则和使用括号的习惯
下一步
运算符是构建程序逻辑的基石。在下一篇文章中,我们将深入探索 Python 中最重要的数据类型之一——字符串,学习其丰富而强大的操作方法。
实践建议:打开 Python REPL 多练习各种运算符的组合。特别建议试试
and/or返回非布尔值的行为,以及链式比较的灵活性。
Summary: 运算符与表达式全面解析。