17.1 运算符概览 #
项目开发中最常用的几类运算符:
| 类型 | 运算符 | 典型用途 |
|---|---|---|
| 算术 | + - * / // % ** |
计算、分页取余 |
| 比较 | == != > < >= <= |
条件判断 |
| 逻辑 | and or not |
组合条件 |
| 赋值 | = += -= … |
累加、计数 |
| 成员 | in not in |
判断是否在序列/字符串中 |
| 身份 | is is not |
判断是否为同一对象(如 None) |
17.2 算术与比较 #
a, b = 10, 3
print(a + b, a // b, a % b) # 13 3 1
print(a / b) # 3.333...(float)
print(a > b, a == b) # True False
17.3 逻辑运算 #
age = 25
is_active = True
if age >= 18 and is_active:
print("可访问")
role = "admin"
if role not in ("guest", "banned"):
print("允许操作")and / or 有短路:左侧已能决定结果时,右侧不再求值
17.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。
17.4 赋值运算符 #
count = 0
count += 1 # 等价 count = count + 1
print(count)
total = 100
total *= 1.08 # 加价 8%
print(total)17.5 is 与 == #
| 运算符 | 比较内容 |
|---|---|
== |
值是否相等 |
is |
是否是同一个对象 |
a = [1, 2]
b = [1, 2]
print(a == b) # True
print(a is b) # False
value = None
if value is None: # 判断 None 用 is
pass17.6 运算符优先级 #
不必背完整表,记住:括号 > 算术 > 比较 > not > and > or。拿不准就加括号。
result = 2 + 3 * 4 # 14,先乘后加
result = (2 + 3) * 4 # 20
# 幂运算从右结合:2 ** 3 ** 2 等价 2 ** (3 ** 2)17.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