一、算术运算符
算术运算符用于执行数学运算。
# 基础算术运算
a = 15
b = 4
print(f"加法:{a} + {b} = {a + b}")
print(f"减法:{a} - {b} = {a - b}")
print(f"乘法:{a} * {b} = {a * b}")
print(f"除法:{a} / {b} = {a / b}")
print(f"整除:{a} // {b} = {a // b}")
print(f"取余:{a} % {b} = {a % b}")
print(f"幂运算:{a} ** {b} = {a ** b}")
实用技巧:整除与取余的应用
# 判断奇偶数
num = 17
if num % 2 == 0:
print(f"{num} 是偶数")
else:
print(f"{num} 是奇数")
# 时间转换:秒转时分秒
total_seconds = 3665
hours = total_seconds // 3600
minutes = (total_seconds % 3600) // 60
seconds = total_seconds % 60
print(f"{total_seconds}秒 = {hours}时{minutes}分{seconds}秒")
# 分页计算
item_index = 35
page_size = 10
page_number = (item_index - 1) // page_size + 1
print(f"第{item_index}条数据在第{page_number}页")
二、比较运算符
比较运算符返回布尔值(True 或 False)。
x = 10
y = 20
print(f"x == y: {x == y}")
print(f"x != y: {x != y}")
print(f"x > y: {x > y}")
print(f"x < y: {x < y}")
print(f"x >= 10: {x >= 10}")
print(f"y <= 20: {y <= 20}")
链式比较(Python 特色)
age = 25
is_adult = 18 <= age <= 60
print(f"{age}岁是成年人吗?{is_adult}")
score = 85
if 90 <= score <= 100:
grade = "A"
elif 80 <= score < 90:
grade = "B"
elif 70 <= score < 80:
grade = "C"
else:
grade = "D"
print(f"成绩等级:{grade}")
三、逻辑运算符
逻辑运算符用于组合多个条件。
print(f"True and False: {True and False}")
print(f"True or False: {True or False}")
print(f"not True: {not True}")
# 用户登录验证
username = "admin"
password = "123456"
is_verified = True
can_login = (username == "admin") and (password == "123456") and is_verified
print(f"可以登录:{can_login}")
# 折扣判断
has_vip = False
has_coupon = True
can_discount = has_vip or has_coupon
print(f"可以享受折扣:{can_discount}")
短路求值
def check():
print("函数被调用了")
return True
result = False and check()
print(f"结果:{result}")
# 提供默认值
user_name = ""
display_name = user_name or "匿名用户"
print(f"显示名称:{display_name}")
四、位运算符
位运算符直接操作二进制位。
a = 12
b = 5
print(f"a & b (按位与): {a & b}")
print(f"a | b (按位或): {a | b}")
print(f"a ^ b (按位异或): {a ^ b}")
print(f"~a (按位取反): {~a}")
print(f"a << 1 (左移): {a << 1}")
print(f"a >> 1 (右移): {a >> 1}")
位运算的实用场景
# 判断奇偶
num = 17
is_odd = num & 1
print(f"{num}是奇数吗?{bool(is_odd)}")
# 快速乘除
x = 10
print(f"{x} * 8 = {x << 3}")
print(f"{x} / 4 = {x >> 2}")
# 权限标志位
READ = 1
WRITE = 2
EXECUTE = 4
user_permission = READ | WRITE
print(f"用户权限值:{user_permission}")
has_write = bool(user_permission & WRITE)
print(f"有写权限:{has_write}")
五、赋值运算符
x = 10
x += 5
print(f"x += 5: {x}")
x -= 3
print(f"x -= 3: {x}")
x *= 2
print(f"x *= 2: {x}")
# 多重赋值
a, b, c = 1, 2, 3
print(f"a={a}, b={b}, c={c}")
# 交换变量
a, b = b, a
print(f"交换后:a={a}, b={b}")
六、成员运算符与身份运算符
# 成员运算符
fruits = ["apple", "banana", "orange"]
print(f"'banana' in fruits: {'banana' in fruits}")
print(f"'grape' not in fruits: {'grape' not in fruits}")
# 身份运算符
a = [1, 2, 3]
b = [1, 2, 3]
c = a
print(f"a == b: {a == b}")
print(f"a is b: {a is b}")
print(f"a is c: {a is c}")
# None 比较
value = None
print(f"value is None: {value is None}")
七、运算符优先级
从高到低:括号 > 幂 > 一元 > 乘除 > 加减 > 位移 > 位与 > 位异或 > 位或 > 比较 > not > and > or
result = 2 + 3 * 4
print(f"2 + 3 * 4 = {result}")
result = (2 + 3) * 4
print(f"(2 + 3) * 4 = {result}")
x, y, z = 10, 5, 2
result = x + y * z ** 2
print(f"x + y * z ** 2 = {result}")
八、实战练习:简易计算器
def calculator(a, b, operator):
operations = {
'+': lambda x, y: x + y,
'-': lambda x, y: x - y,
'*': lambda x, y: x * y,
'/': lambda x, y: x / y if y != 0 else "错误:除数不能为 0",
'//': lambda x, y: x // y if y != 0 else "错误",
'%': lambda x, y: x % y if y != 0 else "错误",
'**': lambda x, y: x ** y,
}
if operator in operations:
return operations[operator](a, b)
return "错误:不支持的运算符"
if __name__ == "__main__":
test_cases = [
(10, 5, '+'), (10, 5, '-'), (10, 5, '*'),
(10, 5, '/'), (10, 3, '//'), (10, 3, '%'),
(2, 8, '**'), (10, 0, '/'),
]
for a, b, op in test_cases:
result = calculator(a, b, op)
print(f"{a} {op} {b} = {result}")
九、今日要点总结
| 运算符类型 | 符号 | 说明 | |
|---|---|---|---|
| 算术 | + - * / // % ** | 基础数学运算 | |
| 比较 | == != > < >= <= | 返回布尔值 | |
| 逻辑 | and or not | 条件组合 | |
| 位运算 | & | ^ ~ << >> | 二进制操作 |
| 赋值 | = += -= *= | 变量赋值 | |
| 成员 | in not in | 成员检查 | |
| 身份 | is is not | 对象身份比较 |
关键记忆点:
- Python 支持链式比较:18 <= age <= 60
- 逻辑运算符有短路特性
- is 比较身份,== 比较值
- 用括号明确表达式优先级
- 位运算在权限控制中非常有用