Skip to content

逻辑运算符

and 与运算符

and 具有短路效果,即如果第一个操作数为 False,则不会评估第二个操作数

and 返回的不一定是布尔值,如果左边是假,直接返回左边的操作数,否则返回右边的操作数

python
# and 与运算符
# 只有当两个操作数都为 True 时,结果才为 True
print(True and True)  # True
print(True and False)  # False
print(False and True)  # False
print(False and False)  # False

print(1 and 2)  # 2
print(0 and 2)  # 0

or 或运算符

or 具有短路效果

or 返回的不一定是布尔值,如果左边是真,直接返回左边的操作数,否则返回右边的操作数

python
# or 或运算符
# 只有当两个操作数都为 False 时,结果才为 False
print(True or True)  # True
print(True or False)  # True
print(False or True)  # True
print(False or False)  # False

print(1 or 2)  # 1
print(0 or 2)  # 2

not 非运算符

python
# not 非运算符
# 对操作数进行取反操作
print(not True)  # False
print(not False)  # True

in 与 not in 成员运算符

in 运算符用于判断一个值是否在序列中

not in 运算符用于判断一个值是否不在序列中

python
# in 成员运算符
# 用于判断一个值是否在序列中
print(1 in [1, 2, 3])  # True
print(4 in [1, 2, 3])  # False

print("a" in "hello")  # True
print("b" in "hello")  # False

# not in 成员运算符
# 用于判断一个值是否不在序列中
print(1 not in [1, 2, 3])  # False
print(4 not in [1, 2, 3])  # True

print("a" not in "hello")  # False
print("b" not in "hello")  # True

is 与 is not 身份运算符

is 运算符用于判断两个变量是否引用自同一个对象

is not 运算符用于判断两个变量是否引用自不同的对象

python
# is 身份运算符
# 用于判断两个变量是否引用自同一个对象
a = [1, 2, 3]
b = a
print(a is b)  # True

c = [1, 2, 3]
print(a is c)  # False

# is not 身份运算符
# 用于判断两个变量是否引用自不同的对象
print(a is not b)  # False
print(a is not c)  # True

Released under the MIT License.