模式切换
运算符
在 Python 中,运算符用于执行各种算术运算、比较运算、逻辑运算以及其他操作。
算术运算符
+: 加法
python
result = 5 + 3 # result 是 8-: 减法
python
result = 5 - 3 # result 是 2*: 乘法
python
result = 5 * 3 # result 是 15/: 除法(返回浮点数)
python
result = 5 / 3 # result 是 1.6666666666666667//: 地板除法(返回整数,丢弃小数部分)
python
result = 5 // 3 # result 是 1%: 取模(返回除法余数)
python
result = 5 % 3 # result 是 2**: 幂运算
python
result = 5 ** 2 # result 是 25//=: 地板除法赋值
python
a = 5
a //= 3 # a 现在是 1%=: 取模赋值
python
a = 5
a %= 3 # a 现在是 2**=: 幂赋值
python
a = 5
a **= 2 # a 现在是 25比较运算符
==: 等于
python
result = (5 == 3) # result 是 False!=: 不等于
python
result = (5 != 3) # result 是 True>: 大于
python
result = (5 > 3) # result 是 True<: 小于
python
result = (5 < 3) # result 是 False>=: 大于等于
python
result = (5 >= 3) # result 是 True<=: 小于等于
python
result = (5 <= 3) # result 是 False赋值运算符
=: 赋值
python
a = 5+=: 加法赋值
python
a = 5
a += 3 # a 现在是 8-=: 减法赋值
python
a = 5
a -= 3 # a 现在是 2*=: 乘法赋值
python
a = 5
a *= 3 # a 现在是 15/=: 除法赋值
python
a = 5
a /= 3 # a 现在是 1.6666666666666667%=: 取模赋值
python
a = 5
a %= 3 # a 现在是 2**=: 幂赋值
python
a = 5
a **= 2 # a 现在是 25//=: 地板除法赋值
python
a = 5
a //= 3 # a 现在是 1逻辑运算符
and: 与
python
result = (True and False) # result 是 Falseor: 或
python
result = (True or False) # result 是 Truenot: 非
python
result = not True # result 是 False位运算符
&: 按位与
python
result = 5 & 3 # result 是 1|: 按位或
python
result = 5 | 3 # result 是 7^: 按位异或
python
result = 5 ^ 3 # result 是 6~: 按位取反
python
result = ~5 # result 是 -6<<: 左移
python
result = 5 << 1 # result 是 10>>: 右移
python
result = 5 >> 1 # result 是 2其他运算符
in: 检查某个值是否存在于某个序列中
python
result = (3 in [1, 2, 3, 4]) # result 是 Truenot in: 检查某个值是否不存在于某个序列中
python
result = (3 not in [1, 2, 4]) # result 是 Trueis: 判断两个对象是否为同一个对象(比较的是对象的身份)
python
a = [1, 2, 3]
b = a
result = (a is b) # result 是 Trueis not: 判断两个对象是否不是同一个对象
python
a = [1, 2, 3]
b = [1, 2, 3]
result = (a is not b) # result 是 True