1. 运算符概览 #

类型 运算符 典型用途
算术 + - * / // % ** 计算、分页取余
比较 == != > < >= <= 条件判断
逻辑 and or not 组合条件
赋值 = += -= … 累加、计数
成员 in not in 判断是否在序列/字符串中
身份 is is not 判断是否为同一对象(如 None)

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

3. 逻辑运算 #

age = 25
is_active = True

if age >= 18 and is_active:
    print("可访问")

role = "admin"
if role not in ("guest", "banned"):
    print("允许操作")

3.1 常用技巧:or 设置默认值 #

user_input = None
name = user_input or "匿名"
print(name)

config = {"port": 8080}
port = config.get("port") or 8080
print(port)

4. 赋值运算符 #

count = 0
count += 1          # 等价 count = count + 1
print(count)

total = 100
total *= 1.08       # 加价 8%
print(total)

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
    pass

6. 运算符优先级 #

result = 2 + 3 * 4      # 14,先乘后加
result = (2 + 3) * 4    # 20

# 幂运算从右结合:2 ** 3 ** 2 等价 2 ** (3 ** 2)

7. 项目开发要点 #