一、什么是赋值运算符?
赋值运算符用于将值“装进”变量里——最基础的=就是赋值运算符。
# 基本赋值name = "小明"# 把"小明"赋给nameage = 18# 把18赋给age
二、7种赋值运算符
| | | |
= | 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 | |
三、基本赋值 =
3.1 单个变量赋值
# 给变量赋值name = "张三"age = 25score = 95.5is_student = Trueprint(name, age, score, is_student) # 张三 25 95.5 True
3.2 多个变量同时赋值
# 方式1:一行给多个变量赋值a, b, c = 1, 2, 3print(a, b, c) # 1 2 3# 交换两个变量的值x = 10y = 20x, y = y, x # 交换print(x, y) # 20 10# 方式2:多个变量赋相同值m = n = p = 0print(m, n, p) # 0 0 0
3.3 解包赋值
# 列表解包fruits = ["苹果", "香蕉", "橙子"]a, b, c = fruitsprint(a) # 苹果print(b) # 香蕉print(c) # 橙子# 字符串解包x, y, z = "ABC"print(x, y, z) # A B C# 只取部分(用*)numbers = [1, 2, 3, 4, 5]first, *middle, last = numbersprint(first) # 1print(middle) # [2, 3, 4]print(last) # 5
四、增强赋值运算符
4.1 加等于 +=
# 数字累加count = 0count += 1# count = count + 1print(count) # 1count += 5# count = count + 5print(count) # 6# 字符串拼接message = "Hello"message += " "message += "World"print(message) # Hello World# 列表追加items = [1, 2]items += [3, 4] # items = items + [3, 4]print(items) # [1, 2, 3, 4]
4.2 减等于 -=
# 数字递减health = 100health -= 10# health = health - 10print(health) # 90health -= 20# health = health - 20print(health) # 70# 只能用于数字# name = "张三"# name -= "李" # TypeError
4.3 乘等于 *=
# 数字乘法price = 10price *= 3# price = price * 3print(price) # 30# 字符串重复symbol = "*"symbol *= 20# symbol = symbol * 20print(symbol) # ********************# 列表重复pattern = [1, 2]pattern *= 3# pattern = pattern * 3print(pattern) # [1, 2, 1, 2, 1, 2]
4.4 除等于 /=
# 除法(结果是浮点数)total = 100total /= 4# total = total / 4print(total) # 25.0total /= 2# total = total / 2print(total) # 12.5# 注意:结果一定是浮点数x = 10x /= 2print(x) # 5.0
4.5 整除等于 //=
# 整除x = 10x //= 3# x = x // 3print(x) # 3x = 10.5x //= 3# x = x // 3print(x) # 3.0(结果还是浮点数)
4.6 取余等于 %=
# 取余数x = 10x %= 3# x = x % 3print(x) # 1# 判断奇偶num = 7num %= 2print(num) # 1(奇数)# 每隔一段时间执行counter = 0whileTrue: counter %= 5# 限制在0-4循环print(f"第{counter}次") counter += 1if counter > 10:break
4.7 幂等于 **=
# 幂运算x = 2x **= 3# x = x ** 3print(x) # 8x = 3x **= 2# x = x ** 2print(x) # 9# 开方y = 9y **= 0.5# 平方根print(y) # 3.0
五、赋值运算符的特性
5.1 赋值不会返回结果
# 赋值语句没有返回值# print(x = 5) # 语法错误# 不能这样写# if x = 5: # 语法错误,应该是 x == 5# print("x等于5")
5.2 链式赋值从右向左
# 从右向左执行x = y = z = 0# 等价于:z = 0; y = z; x = yprint(x, y, z) # 0 0 0# 复杂链式a = b = c = [1, 2, 3]a.append(4)print(a) # [1, 2, 3, 4]print(b) # [1, 2, 3, 4] 注意:b也变了print(c) # [1, 2, 3, 4] 指向同一个列表
5.3 不可变类型 vs 可变类型
# 不可变类型(数字、字符串、元组)x = 10y = xx += 5print(x) # 15print(y) # 10(y不变)# 可变类型(列表、字典)a = [1, 2, 3]b = aa += [4, 5] # 相当于 a.extend([4, 5])print(a) # [1, 2, 3, 4, 5]print(b) # [1, 2, 3, 4, 5] b也变了
六、实战案例
案例1:计数器
defcounter_demo():"""计数器的各种用法"""# 1. 简单计数 count = 0 count += 1 count += 1 count += 1print(f"简单计数:{count}") # 3# 2. 循环计数 total = 0for i inrange(1, 6): total += iprint(f"1-5累加:{total}") # 15# 3. 条件计数 scores = [85, 92, 78, 63, 95, 47] passed = 0 failed = 0for score in scores:if score >= 60: passed += 1else: failed += 1print(f"及格:{passed}人,不及格:{failed}人")# 4. 加权计数 weight = 0 weight += 2 weight *= 1.5 weight **= 2print(f"加权结果:{weight}")# counter_demo()
案例2:购物车总价计算
defshopping_cart():"""购物车价格计算"""# 商品列表 cart = [ {"name": "苹果", "price": 8.5, "quantity": 3}, {"name": "香蕉", "price": 5.0, "quantity": 2}, {"name": "牛奶", "price": 12.5, "quantity": 2}, {"name": "面包", "price": 9.0, "quantity": 1} ]# 使用赋值运算符计算总价 total = 0 discount = 0 tax = 0for item in cart: subtotal = item["price"] * item["quantity"] total += subtotalprint(f"{item['name']}: {subtotal:.2f}元")print(f"\n小计:{total:.2f}元")# 满减优惠if total >= 200: discount += 30print(f"满200减30:-{discount}元")elif total >= 100: discount += 10print(f"满100减10:-{discount}元") total -= discount# 计算税费 tax = total * 0.06 total += taxprint(f"税费(6%):+{tax:.2f}元")print(f"应付:{total:.2f}元")# 找零 paid = 200 change = paid change -= totalprint(f"付款:{paid}元,找零:{change:.2f}元")# shopping_cart()
案例3:游戏角色状态
classGameCharacter:"""游戏角色类"""def__init__(self, name):self.name = nameself.hp = 100# 生命值self.mp = 50# 魔法值self.attack = 20# 攻击力self.defense = 10# 防御力self.level = 1# 等级self.exp = 0# 经验值deftake_damage(self, damage):"""受到伤害""" actual_damage = max(1, damage - self.defense)self.hp -= actual_damageifself.hp < 0:self.hp = 0print(f"{self.name} 受到 {actual_damage} 点伤害,剩余 HP:{self.hp}")return actual_damagedefheal(self, amount):"""治疗"""self.hp += amountifself.hp > 100:self.hp = 100print(f"{self.name} 恢复 {amount} 点生命,当前 HP:{self.hp}")defgain_exp(self, amount):"""获得经验"""self.exp += amountprint(f"{self.name} 获得 {amount} 点经验")# 升级判断whileself.exp >= self.level * 100:self.exp -= self.level * 100self.level += 1self.attack += 5self.defense += 2self.hp = 100# 升级回满血print(f"✨ 升级啦!当前等级:{self.level}")defuse_skill(self, skill_name, mp_cost):"""使用技能"""ifself.mp >= mp_cost:self.mp -= mp_costprint(f"{self.name} 使用 {skill_name},剩余 MP:{self.mp}")returnTrueelse:print("MP 不足!")returnFalsedefshow_status(self):"""显示状态"""print("\n" + "=" * 40)print(f"角色:{self.name}")print(f"HP:{self.hp}/100")print(f"MP:{self.mp}/50")print(f"攻击:{self.attack} 防御:{self.defense}")print(f"等级:{self.level} 经验:{self.exp}/{self.level*100}")print("=" * 40)# 游戏过程hero = GameCharacter("勇者")hero.show_status()hero.take_damage(30)hero.take_damage(25)hero.heal(20)hero.use_skill("火球术", 10)hero.gain_exp(120)hero.gain_exp(150)hero.show_status()
案例4:银行账户管理
classBankAccount:"""银行账户类"""def__init__(self, owner, balance=0):self.owner = ownerself.balance = balanceself.transactions = []defdeposit(self, amount):"""存款"""if amount > 0:self.balance += amountself.transactions.append(f"存款 +{amount}")print(f"存款成功!当前余额:{self.balance:.2f}元")returnTruereturnFalsedefwithdraw(self, amount):"""取款"""if0 < amount <= self.balance:self.balance -= amountself.transactions.append(f"取款 -{amount}")print(f"取款成功!当前余额:{self.balance:.2f}元")returnTrueelse:print("余额不足或金额无效")returnFalsedeftransfer(self, other, amount):"""转账"""ifself.withdraw(amount): other.deposit(amount)self.transactions.append(f"转账给{other.owner} -{amount}")print(f"转账成功!")returnTruereturnFalsedefapply_interest(self, rate):"""计算利息""" interest = self.balance * rateself.balance += interestself.transactions.append(f"利息 +{interest:.2f}")print(f"获得利息:{interest:.2f}元")defshow_history(self):"""显示交易记录"""print(f"\n{self.owner} 的交易记录:")for t inself.transactions[-5:]: # 只显示最近5条print(f" {t}")# 使用示例acc1 = BankAccount("张三", 1000)acc2 = BankAccount("李四", 500)acc1.deposit(500) # 余额 += 500acc1.withdraw(200) # 余额 -= 200acc1.transfer(acc2, 300) # 余额 -= 300,acc2余额 += 300acc1.apply_interest(0.02) # 余额 *= 1.02acc1.show_history()print(f"\n张三余额:{acc1.balance}")print(f"李四余额:{acc2.balance}")
案例5:数据分析统计
defdata_analysis():"""使用赋值运算符进行数据统计""" data = [12, 35, 28, 91, 45, 67, 83, 56, 39, 74]# 初始化统计量 total = 0 max_value = float('-inf') min_value = float('inf') count = 0 sum_squares = 0# 遍历数据for num in data: total += num count += 1 sum_squares += num ** 2if num > max_value: max_value = numif num < min_value: min_value = num# 计算平均值 average = total average /= count# 计算方差:E(X²) - [E(X)]² variance = sum_squares variance /= count variance -= average ** 2# 标准差 std_dev = variance ** 0.5# 输出结果print(f"原始数据:{data}")print(f"数据个数:{count}")print(f"总和:{total}")print(f"平均值:{average:.2f}")print(f"最大值:{max_value}")print(f"最小值:{min_value}")print(f"方差:{variance:.2f}")print(f"标准差:{std_dev:.2f}")# 归一化处理 normalized = []for num in data: norm = (num - min_value) / (max_value - min_value) normalized.append(norm)print(f"归一化后:{[round(n, 2) for n in normalized]}")# data_analysis()
七、常见错误与注意事项
错误1:赋值运算符两边必须有变量
# ❌ 错误5 += 3# 左边不能是常量# ✅ 正确x = 5x += 3
错误2:混淆赋值和比较
# ❌ 常见错误if x = 5: # 应该是 x == 5print("x等于5")# ✅ 正确if x == 5:print("x等于5")
错误3:变量未定义
# ❌ 错误total += 10# total 还没定义# ✅ 正确total = 0total += 10
错误4:类型不匹配
# ❌ 错误x = "Hello"x += 10# 字符串不能加数字# ✅ 正确x = "Hello"x += str(10) # Hello10# 或者x = "Hello"x += "10"
八、赋值运算符速查表
| | | |
= | 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 | |
九、记忆口诀
赋值运算符家族大基本等号最基础增强赋值七个娃加等减等乘等除整除取余和幂等加等常用于计数循环累加少不了减等常用扣血量乘等重复字符串除等结果是浮点取余限制循环圈幂等计算乘方快左边必须是变量右边可以是表达式代码简洁又高效从此告别重复写