Skip to main content
Documents
Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Back to homepage

Basic Operations (基本运算)

✅ 1. 算术运算(Arithmetic Operators)

运算符 说明 示例 结果
+ 加法 3 + 2 5
- 减法 5 - 3 2
* 乘法 4 * 2 8
/ 除法(总是得到 float) 5 / 2 2.5
// 整除 5 // 2 2
% 取余数 5 % 2 1
** 幂运算 2 ** 3 8

常见坑:

5 / 2  # 2.5 (永远是 float)
True + 1  # 2 (布尔值是 0 和 1)

✅ 2. 比较运算(Comparison Operators)

运算符 意义 示例 结果
== 等于 2 == 2 True
!= 不等于 1 != 2 True
> 大于 5 > 3 True
< 小于 3 < 5 True
>= 5 >= 5 True
<= 3 <= 5 True

✅ 3. 逻辑运算(Logical Operators)

运算符 示例 结果
and True and False False
or True or False True
not not True False

短路机制:

a = None
b = a or "default"   # "default"

✅ 4. 赋值运算(Assignment Operators)

运算 示例 等价
= x = 10 直接赋值
+= x += 3 x = x + 3
-= x -= 2 x = x - 2
*= x *= 5 x = x * 5
/= x /= 2 x = x / 2
//= x //= 2 假的整除
%= x %= 3 取余
**= x **= 2

✅ 5. 成员运算(Membership Operators)

运算符 示例 结果
in "a" in "abc" True
not in 3 not in [1,2] True

✅ 6. 身份运算(Identity Operators)

运算符 示例 结果
is a is b 是否同一个对象
is not a is not b 否?

例:

a = [1,2]
b = [1,2]
a == b   # True (值相等)
a is b   # False (不是同一对象)

✅ 7. 位运算(Bitwise Operators)

适用于整数:

运算 含义 示例 结果
& 按位与 5 & 3 1
| 按位或 5 | 3 7
^ 按位异或 5 ^ 3 6
~ 按位取反 ~5 -6
<< 左移 5 << 1 10
>> 右移 5 >> 1 2

✅ 8. 字符串运算(String Operations)

运算 示例 结果
拼接 "a" + "b" “ab”
重复 "a" * 3 “aaa”
成员 "a" in "abc" True

字符串是不可变,不能:

s[0] = "x"  # ❌

✅ 9. 列表运算(List Operations)

运算 示例
拼接 [1,2] + [3]
重复 [0] * 3 -> [0,0,0]
成员 2 in [1,2,3]

列表可变:

lst.append(4)
lst[0] = 99

✅ 10. 字典运算(Dict Operations)

成员(检查键)

"a" in {"a": 1}   # True

合并

{**a, **b}

🌟 11. Python 运算的隐藏机制

① 整数缓存(-5 到 256)

a = 100
b = 100
a is b   # True

② 短路逻辑(性能常用)

x = a and b  # 如果 a 为 False,直接返回 a

③ 字符串驻留(interning)

小字符串可能共享对象。

🚀 12. Python 运算最佳实践

  • 使用 += 而不是 x = x + ...
  • 字符串拼接使用 join(高性能)
  • 用 // 而不是 / 再转 int
  • 数字精度推荐使用 Decimal
  • 字典合并用 {**a, **b}a | b(3.9+)

💎 13. 最终速查总结(收藏)

类别 示例
算术 +, -, *, /, //, %, **
比较 == != > < >= <=
逻辑 and or not
赋值 += -= *= /=
成员 in not in
身份 is is not
位运算 & | ^ ~ << >>