运算符
约 1058 字大约 4 分钟
2025-04-03
比较运算符
比较运算符主要有六个:
>
:大于<
:小于>=
:大于等于<=
:小于等于==
:等于!=
:不等于
比较运算返回的值为 True
或 False
。
算术运算符
Python 中的算术运算符有七个:
+
:加和-
:相减*
:相乘/
:相除//
:整除 | 地板除(向下取整)**
:幂运算%
:取余(模)
算术运算主要用于数字的计算。字符串也可以用 +
和 *
进行拼接。
赋值运算符
赋值运算符为 =
。在 Python 中,为了输入简便,还从其中算术运算符中衍生出了七种赋值运算符:+=
,-=
, *=
, /=
, //=
, **=
, %=
。它们的用法和含义如下:
a = 10
b = 2
b += 1 # b = b + 1
a -= 1 # a = a - 1
a *= 2 # a = a * 2
a /= 2 # a = a / 2
a //= 2 # a = a // 2
a **= 2 # a = a ** 2
a %= 2 # a = a % 2
逻辑运算符
逻辑运算符有三个:与(and
,并且)、或(or
)、非(not
,不是)。
逻辑运算的优先级是 () > not > and > or
,查找顺序为从左向右。例如:
3>2 and 4>2 or True and not False and True
# 先运算比较
True and True or True and not False and True
# 再运算 not
True and True or True and True and True
# 运算 and
True or True
# 最后运算 or
True
当数字之间进行逻辑运算时,有这样一套规则:
and 数字进行逻辑运算时:
两边都不为 0 和 False 时,选择 and 后边的内容
两边都为假时,选择 and 前的内容
一真一假选择假
or 数字进行逻辑运算时:
两边都不为 0 和 False 时,选择 or 前边的内容
两边都为假时,选择 or 后边的内容
一真一假选择真
官方给出的运算规则是这个样子的:
操作 | 返回值 |
---|---|
x or y | 如果 x 为假,返回 y,否则返回 x |
x and y | 如果 x 为假,返回 x,否则返回 y |
not x | 如果 x 为假,返回 True,否则返回 False |
可以通过下面的示例来找到这些规律:
print(1 and 3)
print(0 and 8)
print(9 and 4)
print(False and 5)
成员运算符
在 Python 中,成员运算符有两个:
a in b
:用于判断a
是否在b
中a not in b
:用于判断a
是否不在b
中
具体使用示例:
name = "alice"
msg = input(">>>")
if name in msg:
print(111)
else:
print(222)
输出结果为:
>>>alicebob
111
>>>bobtom
222
标识号比较运算符
与成员运算符类似,标识号比较运算符也有两个:
a is b
:用于判断a
和b
是否是同一个对象a is not b
:用于判断a
和b
是否不是同一个对象
is
运算用来表示两个对象是否指向同一个内存地址。 一个对象的内存地址可使用 id()
函数来查看。需要注意的是,is
一般只会用来比较变量而不会用来比较字面量,如果真这么做了虽然不会报错,但是会有警告
a = '张三'
b = '张三'
c = a
print(id(a)) # 4305017376
print(id(b)) # 4305017696
print(id(c)) # 4305017376
print(a is b) # False
print(a is c) # True
print(a is not b) # True
print(a == b) # True
print(a is 1) # False 同时有警告 SyntaxWarning: "is" with 'int' literal
这里有个知识点,当 a
和 b
为相同的比较小的数字(这个范围可能和 Python 版本有关,例如 Python3.13 版本是大于等于 -5
小于等于 256
)时,他们的内存地址是相同的。而当他们是比较大的数字时,即便数值一样,也会存储在不同的内存地址。这个特性是 Python 暂存机制的一种,小数据池机制。暂存机制会在Python 垃圾回收机制中详细讨论
# 当 a 和 b 相等且是小数字时,他们的内存地址相同,a is b 为 True
a = 1
b = 1
print(id(a)) # 4320471696
print(id(b)) # 4320471696
print(a is b) # True
# 当 a 和 b 相等但是大数字时,他们的内存地址不同,a is b 为 False,但是 a == b 仍为 True
a = 1000000000000000000000000000
b = 1000000000000000000000000000
print(id(a)) # 4305107872
print(id(b)) # 4305108352
print(a is b) # False
print(a == b) # True
版权所有
版权归属:Shuo Liu