python中的运算符

一、运算符分类

类别 运算符 说明
算术运算符 + - * / // % ** 数学运算
比较运算符 == != > < >= <= 比较大小
赋值运算符 = += -= *= /= %= **= //= 赋值操作
逻辑运算符 and or not 逻辑判断
位运算符 & ` ^` `~` `<<` `>>`
成员运算符 in not in 成员检测
身份运算符 is is not 对象身份比较
运算符优先级 () ** * / + - 运算顺序

二、算术运算符

1. 基本运算

复制代码
a, b = 10, 3

print(a + b)   # 加法:13
print(a - b)   # 减法:7
print(a * b)   # 乘法:30
print(a / b)   # 除法:3.333...(返回浮点数)
print(a // b)  # 整除:3(返回整数)
print(a % b)   # 取模(余数):1
print(a ** b)  # 幂运算:1000(10³)

# 正负号
print(+5)      # 5
print(-5)      # -5

2. 字符串运算

复制代码
# 字符串拼接
print("Hello" + " " + "World")   # Hello World

# 字符串重复
print("Ha" * 3)                  # HaHaHa
print("-" * 20)                  # --------------------

# 列表重复
print([1, 2] * 3)                # [1, 2, 1, 2, 1, 2]

3. 注意事项

复制代码
# 除法注意
print(10 / 3)    # 3.3333333333333335(浮点数)
print(10 // 3)   # 3(整除)
print(-10 // 3)  # -4(向下取整)

# 类型混合
print(3 + 3.14)  # 6.14(整数自动转浮点数)

# 错误示例
# print("2" + 3)        # TypeError
print(int("2") + 3)     # 5(显式转换)

三、比较运算符

复制代码
a, b = 5, 3

print(a == b)   # False(等于)
print(a != b)   # True(不等于)
print(a > b)    # True(大于)
print(a < b)    # False(小于)
print(a >= b)   # True(大于等于)
print(a <= b)   # False(小于等于)

# 字符串比较(按字典序)
print("apple" < "banana")   # True
print("abc" > "ab")         # True(长度不同)
print("ABC" == "abc")       # False(大小写敏感)

# 链式比较
x = 5
print(1 < x < 10)      # True
print(3 < x > 4)       # True
print(1 < x > 8)       # False

四、赋值运算符

复制代码
# 基本赋值
x = 10

# 复合赋值
x = 5
x += 3      # x = x + 3 → 8
x -= 2      # x = x - 2 → 6
x *= 2      # x = x * 2 → 12
x /= 3      # x = x / 3 → 4.0
x //= 2     # x = x // 2 → 2.0
x %= 3      # x = x % 3 → 2.0
x **= 3     # x = x ** 3 → 8.0

# 多重赋值
a = b = c = 10          # 多个变量赋相同值
print(a, b, c)          # 10 10 10

# 交换变量
x, y = 10, 20
x, y = y, x
print(x, y)             # 20 10

# 解包赋值
a, b, c = 1, 2, 3
lst = [4, 5, 6]
x, y, z = lst
print(x, y, z)          # 4 5 6

五、逻辑运算符

复制代码
# and(与):两边都为真才为真
print(True and True)    # True
print(True and False)   # False
print(False and True)   # False

# or(或):有一边为真即为真
print(True or False)    # True
print(False or True)    # True
print(False or False)   # False

# not(非):取反
print(not True)         # False
print(not False)        # True

# 短路求值
x = 5
print(x > 0 and x < 10)     # True
print(x > 10 and print("不会执行"))  # False(不执行 print)

# 逻辑运算符的返回值(返回决定结果的操作数)
print(0 and 123)        # 0
print(5 and 10)         # 10
print(0 or 123)         # 123
print(5 or 10)          # 5

# 实际应用
name = input("请输入姓名: ") or "匿名"
print(f"欢迎, {name}")

六、位运算符

1. 位运算基础

复制代码
a, b = 0b1100, 0b1010  # 12, 10

# 按位与 &(都为1才为1)
print(bin(a & b))       # 0b1000 (8)

# 按位或 |(有一个为1就为1)
print(bin(a | b))       # 0b1110 (14)

# 按位异或 ^(不同为1,相同为0)
print(bin(a ^ b))       # 0b0110 (6)

# 按位取反 ~
print(bin(~a))          # -0b1101 (-13)

# 左移 <<(相当于乘以 2^n)
print(a << 1)           # 24
print(bin(a << 1))      # 0b11000

# 右移 >>(相当于除以 2^n)
print(a >> 1)           # 6
print(bin(a >> 1))      # 0b110

2. 位运算应用

复制代码
# 权限管理
READ = 0b100   # 4
WRITE = 0b010  # 2
EXECUTE = 0b001# 1

# 设置权限
permission = READ | WRITE  # 0b110 (6)
print(permission & READ != 0)     # True(检查读权限)
print(permission & EXECUTE != 0)  # False

# 添加权限
permission |= EXECUTE
print(permission)         # 7

# 移除权限
permission &= ~WRITE
print(permission)         # 5

# 判断奇偶数
def is_odd(n):
    return n & 1 == 1

print(is_odd(5))   # True
print(is_odd(4))   # False

# 快速乘以/除以 2
n = 16
print(n << 1)      # 32(乘以2)
print(n >> 1)      # 8(除以2)

七、成员运算符

复制代码
# 字符串成员检查
text = "Hello World"
print("Hello" in text)      # True
print("Hi" in text)         # False
print("H" not in text)      # False

# 列表成员检查
fruits = ["apple", "banana", "orange"]
print("apple" in fruits)    # True
print("grape" not in fruits)# True

# 字典成员检查(检查键)
config = {"host": "localhost", "port": 8080}
print("host" in config)     # True
print("port" in config)     # True
print(8080 in config)       # False(值不算)

# 函数应用
def contains_any(text, chars):
    """检查字符串是否包含任意一个字符"""
    return any(c in text for c in chars)

print(contains_any("hello", "aeiou"))  # True

八、身份运算符

复制代码
# is:检查是否同一个对象
a = [1, 2, 3]
b = [1, 2, 3]
c = a

print(a is c)       # True(同一个对象)
print(a is b)       # False(不同对象,内容相同)
print(a == b)       # True(内容相等)

# is not:检查是否不是同一个对象
print(a is not b)   # True

# 整数缓存(小整数 -5 到 256)
x = 256
y = 256
print(x is y)       # True(缓存复用)

x = 257
y = 257
print(x is y)       # False(超出缓存范围)
print(x == y)       # True

# None 比较(推荐使用 is)
value = None
if value is None:   # 推荐
    print("值是 None")
if value == None:   # 不推荐
    print("也是 None")

九、运算符优先级

1. 优先级表(从高到低)

复制代码
# 优先级示例
# 1. 括号 () - 最高优先级
result = (2 + 3) * 4      # 20

# 2. 幂运算 **
result = 2 * 3 ** 2        # 18(先算 3**2=9,再乘2)

# 3. 正负号 +x, -x
result = -3 ** 2           # -9(先算幂,再取负)
result = (-3) ** 2         # 9(括号改变优先级)

# 4. 乘法类 * / // %
result = 2 + 3 * 4         # 14(先乘再加)

# 5. 加法类 + -
result = 10 - 2 + 3        # 11(左到右)

# 6. 比较运算符 == != > < >= <=
result = 2 + 3 > 1 + 4     # False(先算加法再比较)

# 7. 赋值运算符 = - 最低优先级
x = 2 + 3                  # 先算加法再赋值

十、运算符重载

Python 允许通过特殊方法重载运算符的行为。

复制代码
class Vector:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    
    def __add__(self, other):           # 重载 +
        return Vector(self.x + other.x, self.y + other.y)
    
    def __sub__(self, other):           # 重载 -
        return Vector(self.x - other.x, self.y - other.y)
    
    def __mul__(self, scalar):          # 重载 *
        return Vector(self.x * scalar, self.y * scalar)
    
    def __eq__(self, other):            # 重载 ==
        return self.x == other.x and self.y == other.y
    
    def __str__(self):
        return f"Vector({self.x}, {self.y})"

# 使用
v1 = Vector(1, 2)
v2 = Vector(3, 4)

print(v1 + v2)          # Vector(4, 6)
print(v1 - v2)          # Vector(-2, -2)
print(v1 * 3)           # Vector(3, 6)
print(v1 == Vector(1, 2))  # True

备注

  1. 除法注意/ 返回浮点数,// 返回整数

  2. 逻辑短路andor 会短路求值

  3. 比较链式a < b < c 等价于 a < b and b < c

  4. 优先级括号:不确定时用括号明确顺序

  5. 身份比较is 比较对象,== 比较内容

相关推荐
老纪1 小时前
HTML函数工具在NAS设备上能运行吗_轻服务器适配指南【指南】
jvm·数据库·python
老纪1 小时前
SQL如何高效提取大表前几行:分页查询与OFFSET优化
jvm·数据库·python
MrXun_1 小时前
pycharm 无法下载插件,提示网络错误
ide·python·pycharm
m0_470857641 小时前
Python如何构建异步消息队列_利用asyncio配合Redis实现任务分发
jvm·数据库·python
2301_781571421 小时前
SQL嵌套子查询中的变量如何传递_作用域与上下文限制解析
jvm·数据库·python
m0_631529821 小时前
Golang数组和切片有什么区别_Golang数组切片对比教程【通俗】
jvm·数据库·python
2401_880071401 小时前
CSS如何利用Sass实现透明度动态化_通过函数计算CSS颜色值
jvm·数据库·python
iuvtsrt1 小时前
如何进行SQL安全基线评估_定期核对数据库安全配置
jvm·数据库·python
Jetev1 小时前
Python Tkinter自定义对话框怎么写_Toplevel创建子窗口并结合wait_window()实现阻塞
jvm·数据库·python