1. 运算符概览 #
| 类型 |
运算符 |
典型用途 |
| 算术 |
+ - * / // % ** |
计算、分页取余 |
| 比较 |
== != > < >= <= |
条件判断 |
| 逻辑 |
and or not |
组合条件 |
| 赋值 |
= += -= … |
累加、计数 |
| 成员 |
in not in |
判断是否在序列/字符串中 |
| 身份 |
is is not |
判断是否为同一对象(如 None) |
2. 算术与比较 #
- 算术运算符用于数值计算;比较运算符返回布尔值,常用于
if 条件。
a, b = 10, 3
print(a + b, a // b, a % b)
print(a / b)
print(a > b, a == b)
- 注意:
/ 得浮点数,// 得整除(见整数类型、浮点类型章节)。
3. 逻辑运算 #
age = 25
is_active = True
if age >= 18 and is_active:
print("可访问")
role = "admin"
if role not in ("guest", "banned"):
print("允许操作")
and / or 有短路:左侧已能决定结果时,右侧不再求值。
3.1 常用技巧:or 设置默认值 #
user_input = None
name = user_input or "匿名"
print(name)
config = {"port": 8080}
port = config.get("port") or 8080
print(port)
- 左侧为假值(
None、""、0 等)时,取右侧默认值。
- 复杂分支仍用
if-else,不要堆多层 and/or。
4. 赋值运算符 #
+=、-=、*= 等是复合赋值,等价于先运算再赋回变量。
count = 0
count += 1
print(count)
total = 100
total *= 1.08
print(total)
5. is 与 == #
| 运算符 |
比较内容 |
== |
值是否相等 |
is |
是否是同一个对象 |
a = [1, 2]
b = [1, 2]
print(a == b)
print(a is b)
value = None
if value is None:
pass
6. 运算符优先级 #
- 不必背完整表,记住:括号 > 算术 > 比较 >
not > and > or。
- 拿不准就加括号。
result = 2 + 3 * 4
result = (2 + 3) * 4
7. 项目开发要点 #
- 金额、比例:注意
/ 与 //、浮点精度(用 Decimal)。
- 判断成员:
if key in dict、if "@" in email 比手动遍历更清晰。
None 用 is:不要写 == None。
- 默认值用
or:name or "默认";注意 0、"" 也会触发默认值,需区分时用 if x is not None。
- 表达式别太绕:多步逻辑拆成变量或
if,可读性优先。
- 字符串:
"a" + "b" 拼接,"hi" * 3 重复;大量拼接用 join。