Python 运算符

Python 运算符

目录


算术运算符

用于执行基本的数学运算。

运算符 名称 示例 结果
+ 加法 5 + 3 8
- 减法 10 - 4 6
* 乘法 3 * 7 21
/ 除法 10 / 3 3.333...
// 整除 10 // 3 3
% 取模(求余) 10 % 3 1
** 幂运算 2 ** 3 8

示例代码

python 复制代码
a = 10
b = 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.3333333333333335
print(f"整除: {a} // {b} = {a // b}")     # 3
print(f"取模: {a} % {b} = {a % b}")       # 1
print(f"幂运算: {a} ** {b} = {a ** b}")   # 1000

特殊用法

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

# 字符串重复
print("Hi" * 3)  # HiHiHi

# 列表拼接
list1 = [1, 2, 3]
list2 = [4, 5, 6]
print(list1 + list2)  # [1, 2, 3, 4, 5, 6]

实用技巧

python 复制代码
# 判断奇偶数
num = 7
if num % 2 == 0:
    print(f"{num} 是偶数")
else:
    print(f"{num} 是奇数")

# 提取数字的各位
number = 12345
units = number % 10          # 个位: 5
tens = (number // 10) % 10   # 十位: 4
hundreds = (number // 100) % 10  # 百位: 3
print(f"个位: {units}, 十位: {tens}, 百位: {hundreds}")

赋值运算符

用于给变量赋值。

运算符 示例 等价于
= x = 5 x = 5
+= x += 3 x = x + 3
-= x -= 3 x = x - 3
*= x *= 3 x = x * 3
/= x /= 3 x = x / 3
//= x //= 3 x = x // 3
%= x %= 3 x = x % 3
**= x **= 3 x = x ** 3

示例代码

python 复制代码
x = 10
print(f"初始值: {x}")

x += 5
print(f"x += 5: {x}")    # 15

x -= 3
print(f"x -= 3: {x}")    # 12

x *= 2
print(f"x *= 2: {x}")    # 24

x /= 4
print(f"x /= 4: {x}")    # 6.0

x //= 2
print(f"x //= 2: {x}")   # 3.0

x **= 3
print(f"x **= 3: {x}")   # 27.0

x %= 5
print(f"x %= 5: {x}")    # 2.0

多重赋值

python 复制代码
# 同时给多个变量赋值
a, b, c = 1, 2, 3
print(f"a={a}, b={b}, c={c}")

# 交换变量值(Python 特色)
x, y = 10, 20
print(f"交换前: x={x}, y={y}")
x, y = y, x
print(f"交换后: x={x}, y={y}")

# 解包赋值
numbers = [1, 2, 3, 4, 5]
first, *middle, last = numbers
print(f"第一个: {first}, 中间: {middle}, 最后一个: {last}")
# 输出: 第一个: 1, 中间: [2, 3, 4], 最后一个: 5

比较运算符

用于比较两个值,返回布尔值(True 或 False)。

运算符 名称 示例 结果
== 等于 5 == 5 True
!= 不等于 5 != 3 True
> 大于 5 > 3 True
< 小于 5 < 3 False
>= 大于等于 5 >= 5 True
<= 小于等于 5 <= 3 False

示例代码

python 复制代码
a = 10
b = 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} >= {b}: {a >= b}")  # False
print(f"{a} <= {b}: {a <= b}")  # True

链式比较

Python 支持链式比较,使代码更简洁。

python 复制代码
age = 25

# 传统写法
if age >= 18 and age <= 60:
    print("成年人")

# Python 链式比较(推荐)
if 18 <= age <= 60:
    print("成年人")

# 更多例子
x = 5
print(1 < x < 10)    # True
print(1 < x < 3)     # False
print(10 > x > 0)    # True

常见错误

python 复制代码
# ❌ 错误:使用单个 = 进行比较
# if x = 5:  # SyntaxError

# ✅ 正确:使用 == 进行比较
if x == 5:
    print("x 等于 5")

# ❌ 错误:浮点数直接比较
# print(0.1 + 0.2 == 0.3)  # False(精度问题)

# ✅ 正确:使用近似比较
import math
print(math.isclose(0.1 + 0.2, 0.3))  # True

逻辑运算符

用于组合多个条件表达式。

运算符 名称 说明 示例
and 两者都为 True 才返回 True True and FalseFalse
or 至少一个为 True 就返回 True True or FalseTrue
not 取反 not TrueFalse

真值表

python 复制代码
# and 运算符
print(True and True)    # True
print(True and False)   # False
print(False and True)   # False
print(False and False)  # False

# or 运算符
print(True 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

短路求值

python 复制代码
# and 短路:如果第一个为 False,不再计算第二个
def check():
    print("check 被调用")
    return True

result = False and check()  # check() 不会被调用
print(result)  # False

# or 短路:如果第一个为 True,不再计算第二个
result = True or check()  # check() 不会被调用
print(result)  # True

实际应用

python 复制代码
age = 25
has_license = True

# 判断是否可以开车
if age >= 18 and has_license:
    print("可以开车")
else:
    print("不可以开车")

# 判断是否为周末
day = "Saturday"
if day == "Saturday" or day == "Sunday":
    print("今天是周末")

# 判断是否不为空
name = ""
if not name:
    print("名字不能为空")

# 提供默认值
username = ""
display_name = username or "匿名用户"
print(display_name)  # 匿名用户

位运算符

对整数的二进制位进行操作。

运算符 名称 示例 说明
& 按位与 5 & 3 对应位都为1则为1
` ` 按位或 `5
^ 按位异或 5 ^ 3 对应位不同则为1
~ 按位取反 ~5 0变1,1变0
<< 左移 5 << 1 向左移动指定位数
>> 右移 5 >> 1 向右移动指定位数

示例代码

python 复制代码
a = 5   # 二进制: 0101
b = 3   # 二进制: 0011

print(f"{a} & {b} = {a & b}")   # 1  (0001)
print(f"{a} | {b} = {a | b}")   # 7  (0111)
print(f"{a} ^ {b} = {a ^ b}")   # 6  (0110)
print(f"~{a} = {~a}")           # -6
print(f"{a} << 1 = {a << 1}")   # 10 (1010)
print(f"{a} >> 1 = {a >> 1}")   # 2  (0010)

实用场景

python 复制代码
# 判断奇偶数(位运算方式)
num = 7
if num & 1:
    print(f"{num} 是奇数")
else:
    print(f"{num} 是偶数")

# 快速乘以/除以 2 的幂
x = 10
print(x << 1)   # 20 (x * 2)
print(x << 2)   # 40 (x * 4)
print(x >> 1)   # 5  (x // 2)
print(x >> 2)   # 2  (x // 4)

# 权限管理(位标志)
READ = 1    # 0001
WRITE = 2   # 0010
EXECUTE = 4 # 0100

# 赋予读写权限
permissions = READ | WRITE
print(bin(permissions))  # 0b11

# 检查是否有读权限
if permissions & READ:
    print("有读权限")

# 添加执行权限
permissions |= EXECUTE
print(bin(permissions))  # 0b111

# 移除写权限
permissions &= ~WRITE
print(bin(permissions))  # 0b101

成员运算符

用于测试序列中是否包含某个值。

运算符 说明 示例
in 如果在序列中找到值返回 True 'a' in 'abc'
not in 如果在序列中没找到值返回 True 'x' not in 'abc'

示例代码

python 复制代码
# 字符串
text = "Hello, World!"
print('H' in text)        # True
print('z' in text)        # False
print('xyz' not in text)  # True

# 列表
fruits = ["apple", "banana", "orange"]
print("apple" in fruits)      # True
print("grape" in fruits)      # False
print("grape" not in fruits)  # True

# 元组
colors = ("red", "green", "blue")
print("red" in colors)    # True
print("yellow" in colors) # False

# 字典(检查键)
student = {"name": "张三", "age": 20}
print("name" in student)    # True
print("score" in student)   # False

# 集合
primes = {2, 3, 5, 7, 11}
print(5 in primes)      # True
print(4 in primes)      # False

实际应用

python 复制代码
# 验证用户输入
valid_choices = ["1", "2", "3", "q"]
choice = input("请选择 (1/2/3/q): ")
if choice not in valid_choices:
    print("无效选择")

# 检查敏感词
sensitive_words = ["广告", "spam", "违规"]
comment = "这是一条正常评论"
for word in sensitive_words:
    if word in comment:
        print("评论包含敏感词")
        break
else:
    print("评论通过审核")

# 判断季节
month = 7
spring = [3, 4, 5]
summer = [6, 7, 8]
autumn = [9, 10, 11]
winter = [12, 1, 2]

if month in spring:
    season = "春季"
elif month in summer:
    season = "夏季"
elif month in autumn:
    season = "秋季"
else:
    season = "冬季"
print(f"{month}月是{season}")

身份运算符

用于比较两个对象的内存地址(是否是同一个对象)。

运算符 说明 示例
is 如果两个变量指向同一个对象返回 True a is b
is not 如果两个变量不指向同一个对象返回 True a is not b

示例代码

python 复制代码
# 小整数缓存(-5 到 256)
a = 100
b = 100
print(a is b)       # True(Python 缓存了小整数)

# 大整数
c = 1000
d = 1000
print(c is d)       # False(不同对象)
print(c == d)       # True(值相等)

# 列表
list1 = [1, 2, 3]
list2 = [1, 2, 3]
list3 = list1

print(list1 == list2)   # True(值相等)
print(list1 is list2)   # False(不同对象)
print(list1 is list3)   # True(同一对象)

# None 判断(推荐使用 is)
value = None
if value is None:
    print("值为 None")
if value is not None:
    print("值不为 None")

is vs == 的区别

python 复制代码
# == 比较值是否相等
# is 比较是否是同一个对象(内存地址)

a = [1, 2, 3]
b = [1, 2, 3]

print(a == b)   # True  - 值相同
print(a is b)   # False - 不同对象

c = a
print(a == c)   # True  - 值相同
print(a is c)   # True  - 同一对象

# 查看内存地址
print(id(a))    # 例如: 140234567890
print(id(b))    # 例如: 140234567891(不同)
print(id(c))    # 例如: 140234567890(与 a 相同)

何时使用 is

python 复制代码
# ✅ 推荐:与 None 比较时使用 is
if value is None:
    pass

# ❌ 不推荐:与 None 比较时使用 ==
# if value == None:
#     pass

# ✅ 推荐:判断类型时使用 isinstance()
if isinstance(x, int):
    pass

# ❌ 不推荐:使用 type() 和 is 比较
# if type(x) is int:
#     pass

运算符优先级

从高到低排列:

优先级 运算符 说明
1 () 括号
2 ** 幂运算
3 ~, +, - 按位取反、正负号
4 *, /, //, % 乘、除、整除、取模
5 +, - 加、减
6 <<, >> 位移
7 & 按位与
8 ^ 按位异或
9 ` `
10 ==, !=, >, <, >=, <= 比较
11 is, is not, in, not in 身份、成员
12 not 逻辑非
13 and 逻辑与
14 or 逻辑或

示例

python 复制代码
# 优先级示例
result = 2 + 3 * 4
print(result)  # 14(先乘后加)

result = (2 + 3) * 4
print(result)  # 20(括号优先)

# 复杂表达式
a = 10
b = 5
c = 2
result = a + b * c ** 2
print(result)  # 30(先幂运算,再乘法,最后加法)
# 等价于: 10 + (5 * (2 ** 2)) = 10 + (5 * 4) = 10 + 20 = 30

# 逻辑运算符优先级
result = True or False and False
print(result)  # True(and 优先级高于 or)
# 等价于: True or (False and False) = True or False = True

建议

python 复制代码
# ❌ 不推荐:依赖优先级,可读性差
result = a + b * c - d / e ** f

# ✅ 推荐:使用括号明确优先级
result = a + (b * c) - (d / (e ** f))

记住:当不确定时,使用括号!


实战练习

练习1: 温度转换器

python 复制代码
print("=== 温度转换器 ===")
print("1. 摄氏度转华氏度")
print("2. 华氏度转摄氏度")

choice = input("请选择转换类型 (1/2): ")

if choice == "1":
    celsius = float(input("请输入摄氏温度: "))
    fahrenheit = celsius * 9/5 + 32
    print(f"{celsius}°C = {fahrenheit:.2f}°F")
elif choice == "2":
    fahrenheit = float(input("请输入华氏温度: "))
    celsius = (fahrenheit - 32) * 5/9
    print(f"{fahrenheit}°F = {celsius:.2f}°C")
else:
    print("无效选择")

练习2: 闰年判断器

python 复制代码
year = int(input("请输入年份: "))

# 闰年规则:
# 1. 能被4整除且不能被100整除
# 2. 或者能被400整除
is_leap = (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)

if is_leap:
    print(f"{year} 年是闰年")
else:
    print(f"{year} 年不是闰年")

# 使用链式比较的另一种写法
if year % 400 == 0:
    print(f"{year} 年是闰年")
elif year % 100 == 0:
    print(f"{year} 年不是闰年")
elif year % 4 == 0:
    print(f"{year} 年是闰年")
else:
    print(f"{year} 年不是闰年")

练习3: BMI 计算器

python 复制代码
print("=== BMI 计算器 ===")

height = float(input("请输入身高(米): "))
weight = float(input("请输入体重(公斤): "))

# 计算 BMI
bmi = weight / (height ** 2)

print(f"\n您的 BMI 指数: {bmi:.2f}")

# 判断健康状况
if bmi < 18.5:
    status = "偏瘦"
elif bmi < 24:
    status = "正常"
elif bmi < 28:
    status = "偏胖"
else:
    status = "肥胖"

print(f"健康状况: {status}")

# 计算理想体重范围
min_weight = 18.5 * (height ** 2)
max_weight = 24 * (height ** 2)
print(f"理想体重范围: {min_weight:.1f}kg - {max_weight:.1f}kg")

练习4: 简易加密程序

python 复制代码
def encrypt(text, shift=3):
    """凯撒密码加密"""
    result = ""
    for char in text:
        if char.isalpha():
            # 确定基准 ASCII 码
            base = ord('A') if char.isupper() else ord('a')
            # 移位并处理环绕
            shifted = (ord(char) - base + shift) % 26 + base
            result += chr(shifted)
        else:
            result += char
    return result

def decrypt(text, shift=3):
    """凯撒密码解密"""
    return encrypt(text, -shift)

# 测试
message = "Hello, World!"
encrypted = encrypt(message)
decrypted = decrypt(encrypted)

print(f"原文: {message}")
print(f"加密: {encrypted}")
print(f"解密: {decrypted}")

# 交互式
text = input("\n请输入要加密的文本: ")
shift = int(input("请输入偏移量 (默认3): ") or "3")
encrypted = encrypt(text, shift)
print(f"加密结果: {encrypted}")
print(f"解密结果: {decrypt(encrypted, shift)}")

练习5: 购物车程序

python 复制代码
# 商品列表
products = {
    "1": {"name": "苹果", "price": 5.5},
    "2": {"name": "香蕉", "price": 3.2},
    "3": {"name": "橙子", "price": 4.8},
    "4": {"name": "葡萄", "price": 8.5},
}

cart = {}  # 购物车 {商品ID: 数量}

while True:
    print("\n=== 水果店 ===")
    for pid, product in products.items():
        print(f"{pid}. {product['name']} - ¥{product['price']:.2f}/斤")
    print("c. 查看购物车")
    print("q. 结算退出")
    
    choice = input("请选择商品: ")
    
    if choice in products:
        quantity = float(input("请输入购买数量(斤): "))
        if choice in cart:
            cart[choice] += quantity
        else:
            cart[choice] = quantity
        print(f"已添加 {products[choice]['name']} {quantity} 斤")
        
    elif choice == "c":
        if not cart:
            print("购物车为空")
        else:
            print("\n=== 购物车 ===")
            total = 0
            for pid, quantity in cart.items():
                product = products[pid]
                subtotal = product["price"] * quantity
                total += subtotal
                print(f"{product['name']}: {quantity}斤 × ¥{product['price']:.2f} = ¥{subtotal:.2f}")
            print(f"\n总计: ¥{total:.2f}")
            
    elif choice == "q":
        if cart:
            total = sum(products[pid]["price"] * qty for pid, qty in cart.items())
            print(f"\n应付金额: ¥{total:.2f}")
            
            payment = float(input("请输入支付金额: "))
            change = payment - total
            
            if change >= 0:
                print(f"找零: ¥{change:.2f}")
                print("感谢光临!")
                break
            else:
                print("金额不足,请重新支付")
        else:
            print("购物车为空,再见!")
            break
    else:
        print("无效选择")

常见错误与注意事项

1. 除法运算符混淆

python 复制代码
# / 总是返回浮点数
print(10 / 2)    # 5.0
print(10 / 3)    # 3.3333333333333335

# // 返回整数(向下取整)
print(10 // 2)   # 5
print(10 // 3)   # 3
print(-10 // 3)  # -4(注意:向下取整)

2. 浮点数精度问题

python 复制代码
# ❌ 不要直接比较浮点数
print(0.1 + 0.2 == 0.3)  # False

# ✅ 使用 math.isclose()
import math
print(math.isclose(0.1 + 0.2, 0.3))  # True

# ✅ 或使用 Decimal
from decimal import Decimal
print(Decimal('0.1') + Decimal('0.2') == Decimal('0.3'))  # True

3. 可变对象的赋值

python 复制代码
# ❌ 陷阱:列表引用
list1 = [1, 2, 3]
list2 = list1
list2.append(4)
print(list1)  # [1, 2, 3, 4](list1 也被修改了)

# ✅ 正确:创建副本
list1 = [1, 2, 3]
list2 = list1.copy()  # 或 list2 = list1[:]
list2.append(4)
print(list1)  # [1, 2, 3](不受影响)

4. 逻辑运算符返回值

python 复制代码
# and/or 不一定返回布尔值
print(0 and 5)      # 0(返回第一个假值)
print(3 and 5)      # 5(返回最后一个值)
print(0 or 5)       # 5(返回第一个真值)
print(3 or 5)       # 3(返回第一个真值)

# 利用这个特性设置默认值
name = "" or "默认用户"
print(name)  # 默认用户

5. 增量赋值的陷阱

python 复制代码
# 对于不可变类型,+= 创建新对象
a = 10
print(id(a))
a += 1
print(id(a))  # 不同的 ID

# 对于可变类型,+= 可能修改原对象
list1 = [1, 2, 3]
print(id(list1))
list1 += [4]
print(id(list1))  # 相同的 ID(原地修改)

小结

运算符类型 主要用途 常用程度
算术运算符 数学计算 ⭐⭐⭐⭐⭐
赋值运算符 变量赋值 ⭐⭐⭐⭐⭐
比较运算符 条件判断 ⭐⭐⭐⭐⭐
逻辑运算符 组合条件 ⭐⭐⭐⭐⭐
位运算符 底层操作 ⭐⭐
成员运算符 序列查找 ⭐⭐⭐⭐
身份运算符 对象比较 ⭐⭐⭐

核心要点

  • 算术运算注意 /// 的区别
  • 比较运算善用链式比较
  • 逻辑运算理解短路求值
  • is 用于 None 判断,== 用于值比较
  • 不确定优先级时,使用括号

熟练掌握运算符是编写高效 Python 代码的基础!

相关推荐
zhangzeyuaaa4 小时前
Python 异常机制深度剖析
开发语言·python
Ulyanov4 小时前
打造现代化雷达电子对抗仿真界面 第一篇:tkinter/ttk 现代化高级技巧与复杂布局系统设计
python·信息可视化·系统仿真·雷达电子对抗
wgzrmlrm745 小时前
SQL实现按用户偏好进行分组汇总_自定义聚合规则
jvm·数据库·python
7年前端辞职转AI5 小时前
Python 变量
python·编程语言
7年前端辞职转AI5 小时前
Python 数据类型
python·编程语言
冰块的旅行5 小时前
python环境导出
python
曲幽5 小时前
我用fastapi-scaff搭了个项目,两天工期缩到两小时,老板以为我开挂了
python·api·fastapi·web·celery·cli·db·alembic·fastapi-scaff
半点闲5 小时前
入门 SQLAlchemy 教程:从 0 到 1 创建数据库
数据库·python·sqlite·sqlalchemy
好家伙VCC5 小时前
# 发散创新:基于事件驱动架构的实时日志监控系统设计与实现在现代分布式系统中,**事件驱动编程模型**正
java·python·架构