Appearance
运算符
运算符用于执行各种运算操作。Python 提供了丰富的运算符,包括算术运算符、比较运算符、逻辑运算符等。
运算符分类
text
┌─────────────────────────────────────────────────────────────────┐
│ Python 运算符分类 │
├─────────────────────────────────────────────────────────────────┤
│ 算术运算符:+ - * / // % ** │
│ 比较运算符:== != > < >= <= │
│ 赋值运算符:= += -= *= /= //= %= **= │
│ 逻辑运算符:and or not │
│ 位运算符: & | ^ ~ << >> │
│ 成员运算符:in not in │
│ 身份运算符:is is not │
└─────────────────────────────────────────────────────────────────┘算术运算符
python
# 基本算术运算
a, b = 10, 3
# 加法
print(f"{a} + {b} = {a + b}") # 13
# 减法
print(f"{a} - {b} = {a - b}") # 7
# 乘法
print(f"{a} * {b} = {a * b}") # 30
# 除法(结果为浮点数)
print(f"{a} / {b} = {a / b}") # 3.333...
# 整除(向下取整)
print(f"{a} // {b} = {a // b}") # 3
# 取模(求余数)
print(f"{a} % {b} = {a % b}") # 1
# 幂运算
print(f"{a} ** {b} = {a ** b}") # 1000
# 负数的整除
print(f"-7 // 3 = {-7 // 3}") # -3(向下取整)
print(f"7 // -3 = {7 // -3}") # -3
# 字符串运算
print("Hello" + " World") # 连接
print("Hi" * 3) # 重复
# 列表运算
print([1, 2] + [3, 4]) # [1, 2, 3, 4]
print([1] * 3) # [1, 1, 1]比较运算符
python
# 比较运算符返回布尔值
a, b = 10, 20
# 等于
print(f"{a} == {b}: {a == b}") # False
# 不等于
print(f"{a} != {b}: {a != b}") # True
# 大于
print(f"{a} > {b}: {a > b}") # False
# 小于
print(f"{a} < {b}: {a < b}") # True
# 大于等于
print(f"{a} >= 10: {a >= 10}") # True
# 小于等于
print(f"{b} <= 20: {b <= 20}") # True
# 字符串比较(按字典序)
print("'apple' < 'banana':", 'apple' < 'banana') # True
print("'Apple' < 'apple':", 'Apple' < 'apple') # True(大写字母小)
# 列表比较(逐元素比较)
print([1, 2] < [1, 3]) # True
print([1, 2] < [1, 2, 3]) # True
# 链式比较
x = 5
print(1 < x < 10) # True(等同于 1 < x and x < 10)
print(1 < x <= 5) # True赋值运算符
python
# 基本赋值
x = 10
print(f"x = {x}")
# 加法赋值
x += 5 # 等同于 x = x + 5
print(f"x += 5: {x}") # 15
# 减法赋值
x -= 3 # 等同于 x = x - 3
print(f"x -= 3: {x}") # 12
# 乘法赋值
x *= 2 # 等同于 x = x * 2
print(f"x *= 2: {x}") # 24
# 除法赋值
x /= 4 # 等同于 x = x / 4
print(f"x /= 4: {x}") # 6.0
# 整除赋值
x //= 2 # 等同于 x = x // 2
print(f"x //= 2: {x}") # 3.0
# 取模赋值
x %= 2 # 等同于 x = x % 2
print(f"x %= 2: {x}") # 1.0
# 幂赋值
x **= 3 # 等同于 x = x ** 3
print(f"x **= 3: {x}") # 1.0
# 海象运算符(Python 3.8+)
# 在表达式中赋值
numbers = [1, 2, 3, 4, 5]
if (n := len(numbers)) > 3:
print(f"列表有 {n} 个元素")
# while 循环中使用
import re
text = "Hello 123 World 456"
while (match := re.search(r'\d+', text)):
print(f"找到数字: {match.group()}")
text = text[match.end():]逻辑运算符
python
# and:与运算,两边都为 True 才为 True
print(True and True) # True
print(True and False) # False
print(False and True) # False
# or:或运算,一边为 True 就为 True
print(True or False) # True
print(False or True) # True
print(False or False) # False
# not:非运算,取反
print(not True) # False
print(not False) # True
# 短路求值
# and:如果左边为 False,右边不执行
x = 0
print(x > 0 and 10 / x > 1) # False(不会报错)
# or:如果左边为 True,右边不执行
x = 5
print(x > 0 or 10 / 0) # True(不会报错)
# 实际应用
age = 25
has_id = True
# 检查年龄在范围内且有证件
if age >= 18 and age <= 65 and has_id:
print("允许进入")
# 检查是否是管理员或超级用户
role = "admin"
if role == "admin" or role == "superuser":
print("有管理员权限")
# 使用 not
is_banned = False
if not is_banned:
print("用户未被禁止")位运算符
python
# 位运算符操作整数的二进制位
a, b = 60, 13 # 60 = 0011 1100, 13 = 0000 1101
# 按位与(&):两位都为 1 才为 1
print(f"{a} & {b} = {a & b}") # 12 (0000 1100)
# 按位或(|):一位为 1 就为 1
print(f"{a} | {b} = {a | b}") # 61 (0011 1101)
# 按位异或(^):两位不同为 1
print(f"{a} ^ {b} = {a ^ b}") # 49 (0011 0001)
# 按位取反(~):0 变 1,1 变 0
print(f"~{a} = {~a}") # -61
# 左移(<<):所有位向左移动
print(f"{a} << 2 = {a << 2}") # 240 (1111 0000)
# 右移(>>):所有位向右移动
print(f"{a} >> 2 = {a >> 2}") # 15 (0000 1111)
# 位运算技巧
# 判断奇偶
n = 7
print(f"{n} 是奇数: {n & 1 == 1}") # True
# 交换两个数
x, y = 10, 20
x = x ^ y
y = x ^ y
x = x ^ y
print(f"x={x}, y={y}") # x=20, y=10
# 快速乘除 2 的幂
n = 8
print(f"{n} * 2 = {n << 1}") # 16
print(f"{n} / 2 = {n >> 1}") # 4成员运算符
python
# in:检查元素是否在序列中
fruits = ["苹果", "香蕉", "橙子"]
print("苹果" in fruits) # True
print("葡萄" in fruits) # False
# not in:检查元素是否不在序列中
print("葡萄" not in fruits) # True
# 字符串中检查子串
text = "Hello, Python!"
print("Python" in text) # True
print("Java" in text) # False
# 字典中检查键
person = {"name": "张三", "age": 25}
print("name" in person) # True
print("张三" in person) # False(检查的是键,不是值)
# 集合中检查元素
numbers = {1, 2, 3, 4, 5}
print(3 in numbers) # True
print(6 in numbers) # False
# 元组中检查元素
coordinates = (10, 20, 30)
print(20 in coordinates) # True身份运算符
python
# is:检查两个变量是否引用同一对象
a = [1, 2, 3]
b = a
c = [1, 2, 3]
print(a is b) # True(引用同一对象)
print(a is c) # False(不同对象)
print(a == c) # True(值相同)
# is not:检查两个变量是否引用不同对象
print(a is not c) # True
# 小整数缓存(-5 到 256)
x = 100
y = 100
print(x is y) # True(缓存范围内)
x = 1000
y = 1000
print(x is y) # False(超出缓存范围)
# 字符串缓存
s1 = "hello"
s2 = "hello"
print(s1 is s2) # True
# None 的判断(推荐使用 is)
result = None
if result is None:
print("结果是 None")
# 空列表判断
lst = []
if lst is not None and len(lst) == 0:
print("列表为空但不是 None")运算符优先级
text
优先级从高到低:
┌─────────────────────────────────────────────────────────────────┐
│ 优先级 │ 运算符 │ 说明 │
├─────────────────────────────────────────────────────────────────┤
│ 1 │ ** │ 幂运算 │
│ 2 │ +x -x ~x │ 正负号、按位取反 │
│ 3 │ * / // % │ 乘、除、整除、取模 │
│ 4 │ + - │ 加、减 │
│ 5 │ << >> │ 左移、右移 │
│ 6 │ & │ 按位与 │
│ 7 │ ^ │ 按位异或 │
│ 8 │ | │ 按位或 │
│ 9 │ == != > < >= <= │ 比较运算 │
│ 10 │ is is not │ 身份运算 │
│ 11 │ in not in │ 成员运算 │
│ 12 │ not │ 逻辑非 │
│ 13 │ and │ 逻辑与 │
│ 14 │ or │ 逻辑或 │
│ 15 │ := │ 海象运算符 │
└─────────────────────────────────────────────────────────────────┘python
# 使用括号明确优先级
result = 2 + 3 * 4 # 14(先乘后加)
result = (2 + 3) * 4 # 20(括号改变优先级)
# 复杂表达式
a, b, c = 10, 20, 30
result = a + b * c > 100 and c - a < b
# 等同于:((a + (b * c)) > 100) and ((c - a) < b)
print(result) # True
# 推荐使用括号提高可读性
result = (a + b * c > 100) and (c - a < b)小结
本章我们学习了:
- 算术运算符:+、-、*、/、//、%、**
- 比较运算符:==、!=、>、<、>=、<=
- 赋值运算符:=、+=、-=、*=、/= 等
- 逻辑运算符:and、or、not
- 位运算符:&、|、^、~、<<、>>
- 成员运算符:in、not in
- 身份运算符:is、is not
- 运算符优先级:使用括号明确优先级
下一章,我们将学习 流程控制,了解 Python 的条件语句和循环语句。
