先了解下变量:
https://www.cnblogs.com/poloyy/p/15042257.html
再了解下算术运算符:
https://www.cnblogs.com/poloyy/p/15084527.html
= | 赋值 |
-= | 减法赋值 |
=+ | 加法赋值 |
*= | 乘法赋值 |
/= | 除法赋值 |
%= | 求模赋值 |
**= | 乘方赋值 |
//= | 整数除赋值 |
a = 1 b = 1.0 c = "字符串" d = [1, 2, 3, 4] e = (1, 2, 3, 4) f = {1, 2, 3, 4} g = {1: 1, 2: 2}
python 的特性,可以一行代码,同时给多个变量赋值
# 多变量 a, b = 1, 2 print(a, b) a, b, c, d = 1, 2.0, True, "字符串" print(a, b, c, d) e, f, g, h = [1, 2, 3, 4], (1, 2, 3, 4), {1, 2, 3, 4}, {1: 1, 2: 2} print(e, f, g, h) # 输出结果 1 2 1 2.0 True 字符串 [1, 2, 3, 4] (1, 2, 3, 4) {1, 2, 3, 4} {1: 1, 2: 2}
这是 Python 元组的特性,单个变量使用 = 时,元组在右边的时候可以不用加 ( ),也称为元组打包
# 单个变量 a = 1, True, "字符串" print(a, type(a)) # 输出结果 (1, True, '字符串') <class 'tuple'>
a, b, c = (1, 2, 3) print(a, b, c) a, b, c = [1, 2, 3] print(a, b, c) a, b, c = {1, 2, 3} print(a, b, c) # 输出结果 1 2 3 1 2 3 1 2 3
多重赋值其实就是元组打包和序列解包的组合
a +=1 a = a+1
其他赋值运算符同理,不再重复写
# += a = 1 a += 1 print(a) a +=2.0 print(a) # 输出结果 2 4.0
# -= a = 1 a -= 1 print(a) a -= 1.0 print(a) # 输出结果 0 -1.0
# *= a = 1 a *= 2 print(a) a *= 2.0 print(a) # 输出结果 2 4.0
# **= a = 2 a **= 2 print(a) a **= 2.0 print(a) # 输出结果 4 16.0
# /= a = 2 a /= 2 print(a) a /= 2.0 print(a) # 输出结果 1.0 0.5
# //= a = 5 a //= 2 print(a) a //= 2.0 print(a) # 输出结果 2 1.0
# %= a = 100 a %= 8 print(a) a %= 3.0 print(a) # 输出结果 4 1.0