0 ⽬标
掌握常⽤运算符的作⽤
运算符的分类
算数运算符
赋值运算符
复合赋值运算符
⽐较运算符
逻辑运算符
1. 算数运算符
注意:
混合运算优先级顺序: () ⾼于 ** ⾼于 * / // % ⾼于 + -
2. 赋值运算符
单个变量赋值
num = 1
print(num)
多个变量赋值
num1, float1, str1 = 10, 0.5, 'hello world' print(num1) print(float1) print(str1)
结果如下:
多变量赋相同值
a = b = 10 print(a) print(b)
结果如下:
3. 复合赋值运算符
a = 100 a += 1 # 输出101 a = a + 1,最终a = 100 + 1 print(a) b = 2 b *= 3 # 输出6 b = b * 3,最终b = 2 * 3 print(b) c = 10 c += 1 + 2 # 输出13, 先算运算符右侧1 + 2 = 3, c += 3 , 推导出c = 10 + 3 print(c)
4. ⽐较运算符
⽐较运算符也叫关系运算符, 通常⽤来判断。
a = 7 b = 5 print(a == b) # False print(a != b) # True print(a < b) # False print(a > b) # True print(a <= b) # False print(a >= b) # True
5. 逻辑运算符
a = 1 b = 2 c = 3 print((a < b) and (b < c)) # True print((a > b) and (b < c)) # False print((a > b) or (b < c)) # True print(not (a > b)) # True
5.1 拓展
数字之间的逻辑运算
a = 0 b = 1 c = 2 # and运算符,只要有⼀个值为0,则结果为0,否则结果为最后⼀个⾮0数字 print(a and b) # 0 print(b and a) # 0 print(a and c) # 0 print(c and a) # 0 print(b and c) # 2 print(c and b) # 1 # or运算符,只有所有值为0结果才为0,否则结果为第⼀个⾮0数字 print(a or b) # 1 print(a or c) # 2 print(b or c) # 1
总结
算数运算的优先级
混合运算优先级顺序: () ⾼于 ** ⾼于 * / // % ⾼于 + -
赋值运算符
=
复合赋值运算符
+=
-=
优先级
1. 先算复合赋值运算符右侧的表达式
2. 再算复合赋值运算的算数运算
3. 最后算赋值运算
⽐较运算符
判断相等: ==
⼤于等于: >=
⼩于等于:<=
不等于: !=
逻辑运算符
与: and
或:or
⾮:not