在 Python 中,逻辑运算符用于组合或反转布尔值
在 Python 中,逻辑运算符用于组合或反转布尔值。Python 提供了三个基本的逻辑运算符:and(与)、or(或)、not(非)。这些运算符可以用于布尔值,也可以用于其他类型的值,因为 Python 会将非布尔值视为布尔值进行逻辑运算。
1. and(与)
功能:如果两个操作数都为真,则结果为真。
规则:
如果第一个操作数为假,则返回第一个操作数。
如果第一个操作数为真,则返回第二个操作数。
示例:
python
print(True and ) # 输出: True
print(True and False) # 输出: False
print(False and True) # 输出: False
print(False and False) # 输出: False
# 非布尔值示例
print(3 and 5) # 输出: 5
print(0 and 5) # 输出: 0
print(3 and 0) # 输出: 0
2. or(或)
功能:如果两个操作数中至少有一个为真,则结果为真。
规则:
如果第一个操作数为真,则返回第一个操作数。
如果第一个操作数为假,则返回第二个操作数。
示例:
python
print(True or True) # 输出: True
aspcms.cnprint(True or False) # 输出: True
print(False or True) # 输出: True
print(False or False) # 输出: False
# 非布尔值示例
print(3 or 5) # 输出: 3
print(0 or 5) # 输出: 5
print(0 or "") # 输出: ""
3. not(非)
功能:反转布尔值。
规则:
如果操作数为真,则返回 False。
如果操作数为假,则返回 True。
示例:
python
print(not True) # 输出: False
print(not False) # 输出: True
# 非布尔值示例
print(not 3) # 输出: False
print(not 0) # 输出: True
print(not "") # 输出: True
总结
and 和 or 运算符返回的是第一个和第二个操作数中的一个,而不是简单的布尔值。这种行为称为“短路求值”。
not 运算符总是返回一个布尔值。
Python 中任何非零的数字、非空的序列(如字符串、列表、字典等)都被视为 True,而零、None、空序列等被视为 False。