逻辑运算符 #

逻辑运算符用于组合布尔表达式,返回布尔值或其中一个操作数。

一、逻辑运算符列表 #

运算符 名称 描述 示例
and 两个都为真才为真 True and FalseFalse
or 有一个为真就为真 True or FalseTrue
not 取反 not TrueFalse

二、and 运算符 #

2.1 基本用法 #

python
# 与运算:两个都为真才为真
print(True and True)      # True
print(True and False)     # False
print(False and True)     # False
print(False and False)    # False

2.2 真值表 #

A B A and B
True True True
True False False
False True False
False False False

2.3 返回值特性 #

python
# and返回的是其中一个操作数,不一定是布尔值
print(1 and 2)      # 2(都为真,返回第二个)
print(0 and 2)      # 0(第一个为假,返回第一个)
print(1 and 0)      # 0(第二个为假,返回第二个)
print(0 and 0)      # 0(都为假,返回第一个)

# 字符串
print("hello" and "world")  # "world"
print("" and "world")       # ""(空字符串是假值)

# 列表
print([1] and [2])    # [2]
print([] and [2])     # []

2.4 短路求值 #

python
# and在遇到第一个假值时就停止,不再计算后面的表达式
def expensive_function():
    print("函数被调用")
    return True

# 短路示例
result = False and expensive_function()
# 函数不会被调用
print(result)  # False

# 另一个例子
x = 0
result = x != 0 and 10 / x > 1  # 不会报错
print(result)  # False

2.5 链式and #

python
# 多个and连接
print(True and True and True)     # True
print(True and True and False)    # False

# 返回第一个假值或最后一个真值
print(1 and 2 and 3)              # 3
print(1 and 0 and 3)              # 0
print(1 and 2 and 0 and 4)        # 0

三、or 运算符 #

3.1 基本用法 #

python
# 或运算:有一个为真就为真
print(True or True)       # True
print(True or False)      # True
print(False or True)      # True
print(False or False)     # False

3.2 真值表 #

A B A or B
True True True
True False True
False True True
False False False

3.3 返回值特性 #

python
# or返回的是其中一个操作数
print(1 or 2)       # 1(第一个为真,返回第一个)
print(0 or 2)       # 2(第一个为假,返回第二个)
print(1 or 0)       # 1(第一个为真,返回第一个)
print(0 or 0)       # 0(都为假,返回最后一个)

# 字符串
print("hello" or "world")   # "hello"
print("" or "world")        # "world"

# 列表
print([1] or [2])    # [1]
print([] or [2])     # [2]

3.4 短路求值 #

python
# or在遇到第一个真值时就停止
def expensive_function():
    print("函数被调用")
    return True

result = True or expensive_function()
# 函数不会被调用
print(result)  # True

# 另一个例子
x = 5
result = x > 0 or 10 / 0 > 1  # 不会报错
print(result)  # True

3.5 链式or #

python
# 多个or连接
print(False or False or True)    # True
print(False or False or False)   # False

# 返回第一个真值或最后一个假值
print(0 or 0 or 3)               # 3
print(0 or 2 or 3)               # 2
print(1 or 2 or 0 or 4)          # 1

3.6 设置默认值 #

python
# 使用or设置默认值
name = ""
display_name = name or "Anonymous"
print(display_name)  # "Anonymous"

# 类似的,设置列表默认值
items = None
result = items or []
print(result)  # []

# 注意:这会把0也当作"没有值"
count = 0
result = count or 10
print(result)  # 10(可能不是预期结果)

# 更安全的方式
result = count if count is not None else 10

四、not 运算符 #

4.1 基本用法 #

python
# 非运算:取反
print(not True)     # False
print(not False)    # True

# 数值
print(not 1)        # False
print(not 0)        # True

# 字符串
print(not "hello")  # False
print(not "")       # True

# 列表
print(not [1, 2])   # False
print(not [])       # True

# None
print(not None)     # True

4.2 与布尔值转换的区别 #

python
# not 返回布尔值
print(not 1)        # False
print(not 0)        # True

# bool() 也返回布尔值
print(bool(1))      # True
print(bool(0))      # False

# not x 等价于 not bool(x)
x = 0
print(not x == (not bool(x)))  # True

4.3 常见用法 #

python
# 检查空值
items = []
if not items:
    print("列表为空")

# 检查非空
name = "Tom"
if name:  # 等价于 if not not name
    print("有名字")

# 检查条件不满足
is_valid = False
if not is_valid:
    print("验证失败")

# 检查不在集合中
fruits = ["apple", "banana"]
if "orange" not in fruits:
    print("没有橙子")

五、运算符优先级 #

5.1 优先级顺序 #

python
# 优先级:not > and > or

# 示例
print(True or False and False)  # True
# 等价于 True or (False and False) = True or False = True

print(not True and False)       # False
# 等价于 (not True) and False = False and False = False

5.2 使用括号明确优先级 #

python
# 不使用括号
print(True or False and False)  # True

# 使用括号改变优先级
print((True or False) and False)  # False

# 复杂表达式
a, b, c = True, False, True
result = not a or b and c
# 等价于 (not a) or (b and c) = False or False = False
print(result)  # False

5.3 优先级表 #

优先级 运算符
not
and
or

六、实际应用 #

6.1 条件判断 #

python
age = 25
has_license = True

# 同时满足多个条件
if age >= 18 and has_license:
    print("可以开车")

# 满足任一条件
day = "Saturday"
if day == "Saturday" or day == "Sunday":
    print("周末")

# 复杂条件
score = 85
attendance = 90
if score >= 60 and attendance >= 80:
    print("通过课程")

6.2 输入验证 #

python
def validate_user(username, password):
    # 检查是否为空
    if not username or not password:
        return "用户名和密码不能为空"
    
    # 检查长度
    if len(username) < 3 or len(password) < 6:
        return "用户名或密码太短"
    
    return "验证通过"

print(validate_user("", "123456"))      # 用户名和密码不能为空
print(validate_user("Tom", ""))         # 用户名和密码不能为空
print(validate_user("ab", "123456"))    # 用户名或密码太短

6.3 默认值处理 #

python
# 配置项默认值
config = {
    "timeout": None,
    "retry": 3
}

timeout = config.get("timeout") or 30
retry = config.get("retry") or 1

print(timeout)  # 30(使用默认值)
print(retry)    # 3(使用配置值)

# 更安全的写法
timeout = config.get("timeout", 30)  # 推荐

6.4 链式条件 #

python
# 检查变量在范围内
x = 50
if 0 <= x <= 100:
    print("x在0到100之间")

# 检查多个条件
status = "active"
if status == "active" or status == "pending" or status == "processing":
    print("状态有效")

# 更好的写法
if status in ("active", "pending", "processing"):
    print("状态有效")

七、短路求值的应用 #

7.1 避免错误 #

python
# 避免除零错误
x = 0
result = x != 0 and 10 / x > 1  # 安全

# 避免None属性访问
user = None
name = user and user.name  # 不会报错

# 更好的写法(Python 3.8+)
name = user.name if user else None

7.2 条件执行 #

python
# 使用and执行条件代码
debug = True
debug and print("调试信息")  # 只在debug为True时打印

# 使用or执行默认代码
value = None
value = value or get_default()  # value为假时调用函数

7.3 性能优化 #

python
# 把更可能为假的条件放在and前面
# 把更可能为真的条件放在or前面

# 假设检查缓存很快,检查数据库很慢
if cache_hit() and expensive_database_check():
    print("数据有效")

八、常见陷阱 #

8.1 返回值不是布尔值 #

python
# and和or返回的是操作数,不一定是True/False
result = 1 and 2
print(result)  # 2,不是True
print(type(result))  # <class 'int'>

# 如果需要布尔值
result = bool(1 and 2)
print(result)  # True

8.2 0被当作假值 #

python
count = 0
result = count or 10
print(result)  # 10(可能不是预期)

# 解决方案
count = 0
result = count if count is not None else 10
print(result)  # 0

8.3 复杂表达式的优先级 #

python
a, b, c = True, False, True

# 容易混淆
result = not a or b and c
print(result)  # False

# 使用括号更清晰
result = (not a) or (b and c)
print(result)  # False

九、总结 #

运算符 描述 返回值规则
and 第一个假值或最后一个真值
or 第一个真值或最后一个假值
not 总是返回布尔值

短路求值规则:

  • and:遇到第一个假值停止
  • or:遇到第一个真值停止

优先级: not > and > or

最后更新:2026-03-16