【写在前面】可以参看我的视频学习,喜欢的话,关注,点赞,转发
📚 前言
赋值运算符是编程中最基础也是最重要的概念之一。它们用于给变量赋值,是编写任何程序的基础。本文将详细介绍Python中的各种赋值运算符,并通过丰富的实例帮助你深入理解。
🔤 什么是赋值运算符?
赋值运算符用于将右侧的值赋给左侧的变量。Python提供了多种赋值运算符,从简单的基本赋值到复杂的复合赋值,让代码更加简洁高效。
1️⃣ 基本赋值运算符 (=)
功能:将右侧的值赋给左侧的变量
语法:变量 = 值
示例:
# 基本赋值
name="Python"
age=25
height=1.75
is_student=True
print(f"姓名: {name}")
print(f"年龄: {age}")
print(f"身高: {height}米")
print(f"是否为学生: {is_student}")
输出:
姓名: Python
年龄: 25
身高: 1.75米
是否为学生: True
2️⃣ 加法赋值运算符 (+=)
功能:将右侧的值加到左侧变量上,相当于 变量 = 变量 + 值
语法:变量 += 值
示例:
# 数值加法赋值
score=100
score+=20# 等同于 score = score + 20
print(f"分数增加后: {score}") # 输出: 120
# 字符串拼接赋值
greeting="Hello"
greeting+=" World"# 等同于 greeting = greeting + " World"
print(f"拼接后: {greeting}") # 输出: Hello World
# 列表追加赋值
numbers= [1, 2, 3]
numbers+= [4, 5] # 等同于 numbers = numbers + [4, 5]
print(f"列表追加后: {numbers}") # 输出: [1, 2, 3, 4, 5]
3️⃣ 减法赋值运算符 (-=)
功能:从左侧变量中减去右侧的值,相当于 变量 = 变量 - 值
语法:变量 -= 值
示例:
# 数值减法赋值
temperature=30
temperature-=5# 等同于 temperature = temperature - 5
print(f"温度降低后: {temperature}°C") # 输出: 25°C
# 集合差集赋值
set1= {1, 2, 3, 4, 5}
set1-= {3, 4} # 等同于 set1 = set1 - {3, 4}
print(f"集合差集后: {set1}") # 输出: {1, 2, 5}
4️⃣ 乘法赋值运算符 (*=)
功能:将左侧变量乘以右侧的值,相当于 变量 = 变量 * 值
语法:变量 *= 值
示例:
# 数值乘法赋值
price=50
quantity=3
price*=quantity# 等同于 price = price * quantity
print(f"总价: ¥{price}") # 输出: 总价: ¥150
# 字符串重复赋值
line="-"
line*=20# 等同于 line = line * 20
print(f"分隔线: {line}") # 输出: --------------------
# 列表重复赋值
pattern= [1, 2]
pattern*=3# 等同于 pattern = pattern * 3
print(f"重复模式: {pattern}") # 输出: [1, 2, 1, 2, 1, 2]
5️⃣ 除法赋值运算符 (/=)
功能:将左侧变量除以右侧的值,相当于 变量 = 变量 / 值
语法:变量 /= 值
示例:
# 数值除法赋值
total=100
people=4
per_person=total
per_person/=people# 等同于 per_person = per_person / people
print(f"每人分到: {per_person}") # 输出: 每人分到: 25.0
# 注意:除法总是返回浮点数
number=10
number/=3
print(f"10 ÷ 3 = {number}") # 输出: 10 ÷ 3 = 3.3333333333333335
6️⃣ 整除赋值运算符 (//=)
功能:将左侧变量整除右侧的值,相当于 变量 = 变量 // 值
语法:变量 //= 值
示例:
# 数值整除赋值
total_items=17
boxes=5
items_per_box=total_items
items_per_box//=boxes# 等同于 items_per_box = items_per_box // boxes
print(f"每盒装: {items_per_box}个") # 输出: 每盒装: 3个
remaining=total_items%boxes
print(f"剩余: {remaining}个") # 输出: 剩余: 2个
7️⃣ 取模赋值运算符 (%=)
功能:将左侧变量对右侧的值取模,相当于 变量 = 变量 % 值
语法:变量 %= 值
示例:
# 判断奇偶数
number=27
number%=2# 等同于 number = number % 2
print(f"27 ÷ 2 的余数: {number}") # 输出: 1(奇数)
# 循环计数器
counter=0
foriinrange(1, 11):
counter+=1
ifcounter%3==0:
print(f"第{i}个数是3的倍数")
# 时间计算(小时制)
hours=25
hours%=24# 24小时制转换
print(f"25小时在24小时制中是: {hours}点") # 输出: 1点
8️⃣ 幂赋值运算符 (**=)
功能:将左侧变量的幂次方,相当于 变量 = 变量 ** 值
语法:变量 **= 值
示例:
# 计算平方
side=5
area=side
area**=2# 等同于 area = area ** 2
print(f"边长为{side}的正方形面积: {area}") # 输出: 25
# 复利计算
principal=10000# 本金
rate=1.05# 年利率5%
years=3
amount=principal
amount**=years# 这里应该是 (1+rate)的years次方
# 正确写法:
amount=principal* (rate**years)
print(f"{years}年后金额: ¥{amount:.2f}") # 输出: 15762.50
🎯 综合实例:购物车计算
# 购物车系统演示
print("=== 购物车系统 ===")
# 商品列表
items= [
{"name": "苹果", "price": 5.5, "quantity": 3},
{"name": "香蕉", "price": 3.8, "quantity": 2},
{"name": "橙子", "price": 6.2, "quantity": 4}
]
# 初始化变量
total=0# 总价
item_count=0# 商品种类数
total_quantity=0# 总数量
# 计算总价
foriteminitems:
subtotal=item["price"] *item["quantity"]
total+=subtotal# 累加总价
item_count+=1# 商品种类+1
total_quantity+=item["quantity"] # 总数量+1
print(f"{item['name']}: ¥{item['price']} × {item['quantity']} = ¥{subtotal:.2f}")
print(f"\n商品种类: {item_count}种")
print(f"总数量: {total_quantity}个")
print(f"总计: ¥{total:.2f}")
# 应用折扣
discount_rate=0.9# 9折优惠
final_price=total
final_price*=discount_rate# final_price = final_price * discount_rate
print(f"折扣后: ¥{final_price:.2f}")
# 计算节省金额
saved=total
saved-=final_price# saved = saved - final_price
print(f"节省: ¥{saved:.2f}")
📊 赋值运算符对比表
| 运算符 | 名称 | 等价表达式 | 示例 | 结果 |
|---|
= | 赋值 | x = 5 | x = 10 | x = 10 |
+= | 加法赋值 | x = x + 3 | x = 10; x += 3 | x = 13 |
-= | 减法赋值 | x = x - 3 | x = 10; x -= 3 | x = 7 |
*= | 乘法赋值 | x = x * 3 | x = 10; x *= 3 | x = 30 |
/= | 除法赋值 | x = x / 3 | x = 10; x /= 3 | x = 3.33 |
//= | 整除赋值 | x = x // 3 | x = 10; x //= 3 | x = 3 |
%= | 取模赋值 | x = x % 3 | x = 10; x %= 3 | x = 1 |
**= | 幂赋值 | x = x ** 3 | x = 10; x **= 3 | x = 1000 |
💡 使用技巧
1. 性能优化
复合赋值运算符通常比分开的运算更快:
# 推荐:更高效
count+=1
# 不推荐:相对较慢
count=count+1
2. 代码可读性
选择更直观的表达方式:
# 清晰易懂
total+=price
# 过于复杂,可读性差
total=total+price* (1+tax_rate) /discount
3. 类型一致性
注意运算后的类型变化:
# 整数运算
x=5
x+=3# x 仍然是整数
# 但除法会变成浮点数
x=5
x/=2# x 变成浮点数 2.5
🎓 总结
赋值运算符是Python编程的基础,掌握它们可以:
✅ 让代码更简洁高效
✅ 提高程序性能
✅ 增强代码可读性
✅ 实现复杂的计算逻辑
记住:选择合适的赋值运算符,让你的Python代码更加优雅!
📱 关注我们
想了解更多Python编程技巧?欢迎关注我们的微信公众号,获取更多编程干货!
本文适合Python初学者,建议收藏保存!