Skip to content

运算符与真值:短路、比较链与优先级 ​

真值测试 ​

任何对象都可以在布尔上下文(if、while、and、or)中测试真假。

假值(Falsy):

  • False
  • None
  • 数字零:0、0.0、0j、Decimal(0)、Fraction(0, 1)
  • 空序列:''、()、[]、{}、set()、range(0)
  • 空映射:{}(空字典)
  • 用户定义对象若 __bool__() 返回 False 或 __len__() 返回 0

其他所有值都为真,包括 "False" 字符串、[0] 列表。

python
>>> bool([])
False
>>> bool([0])
True
>>> bool("")
False
>>> bool("False")
True

布尔运算符 ​

not:逻辑非 ​

python
>>> not True
False
>>> not False
True
>>> not []
True
>>> not [1, 2]
False

not 总是返回 True 或 False。

and:逻辑与(短路) ​

x and y:

  • 如果 x 为假,返回 x(不求值 y)
  • 如果 x 为真,返回 y
python
>>> 0 and 10
0
>>> 5 and 10
10
>>> None and "hello"
None
>>> "hello" and "world"
'world'

短路求值:and 一旦遇到假值就停止,不会执行后续表达式:

python
def expensive_check():
    print("执行昂贵检查")
    return True

x = 0
if x > 0 and expensive_check():
    print("条件满足")
# 不会打印 "执行昂贵检查",因为 x > 0 为 False

or:逻辑或(短路) ​

x or y:

  • 如果 x 为真,返回 x(不求值 y)
  • 如果 x 为假,返回 y
python
>>> 5 or 10
5
>>> 0 or 10
10
>>> None or "default"
'default'
>>> "first" or "second"
'first'

实用模式:提供默认值

python
name = input("输入姓名: ") or "匿名"
print(f"你好, {name}")
# 如果输入为空,name 为 "匿名"

链式 or:返回第一个真值或最后一个值

python
>>> None or 0 or "" or "found" or "last"
'found'
>>> None or 0 or ""
''

比较运算符 ​

标准比较 ​

  • == 值相等
  • != 值不等
  • < 小于
  • <= 小于等于
  • > 大于
  • >= 大于等于
  • is 身份相同(同一对象)
  • is not 身份不同
python
>>> 5 == 5.0
True
>>> 5 is 5.0
False
>>> type(5) == type(5.0)
False

比较链 ​

Python 允许链式比较,类似数学表达式:

python
>>> x = 5
>>> 1 < x < 10
True
>>> 1 < x < 4
False

等价于:

python
>>> 1 < x and x < 10
True

但链式比较只求值 x 一次,且短路:

python
def get_value():
    print("计算 x")
    return 5

>>> 1 < get_value() < 10
计算 x
True

get_value() 只调用一次。

多重比较:

python
>>> a, b, c = 1, 2, 3
>>> a < b < c
True
>>> a == 1 < b == 2 < c == 3
True

成员测试 ​

in 和 not in 检查元素是否在序列/集合中:

python
>>> "a" in "apple"
True
>>> 5 in [1, 2, 3]
False
>>> "key" in {"key": "value"}
True

结合 not:

python
>>> 10 not in [1, 2, 3]
True

运算符优先级 ​

从高到低:

  1. ():括号
  2. **:幂运算
  3. +x, -x, ~x:一元运算符
  4. *, /, //, %:乘除模
  5. +, -:加减
  6. <<, >>:位移
  7. &:按位与
  8. ^:按位异或
  9. |:按位或
  10. ==, !=, <, <=, >, >=, is, is not, in, not in:比较
  11. not:逻辑非
  12. and:逻辑与
  13. or:逻辑或

示例:

python
>>> 5 + 3 * 2
11  # 先乘后加
>>> (5 + 3) * 2
16
>>> 2 ** 3 ** 2  # 右结合
512  # 等价于 2 ** (3 ** 2) = 2 ** 9
>>> not 0 and 1
1  # not 0 返回布尔值 True,True and 1 返回操作数 1

建议:复杂表达式使用括号提高可读性,不依赖优先级记忆。

位运算符简介 ​

对整数的二进制位操作:

  • &:按位与
  • |:按位或
  • ^:按位异或
  • ~:按位取反
  • <<:左移
  • >>:右移
python
>>> bin(5)
'0b101'
>>> bin(3)
'0b011'
>>> 5 & 3  # 101 & 011 = 001
1
>>> 5 | 3  # 101 | 011 = 111
7
>>> 5 << 1  # 左移一位 = 乘以 2
10

位运算在底层优化、标志位处理中常见,后续章节深入。

三元表达式 ​

Python 的条件表达式(类似其他语言的 ? :):

python
age = 20
status = "成年" if age >= 18 else "未成年"
print(status)  # 成年

语法:value_if_true if condition else value_if_false

嵌套三元表达式(不推荐,可读性差):

python
score = 85
grade = "A" if score >= 90 else ("B" if score >= 80 else "C")

复杂逻辑用 if-elif-else 更清晰。

实用模式 ​

设置默认值 ​

python
config = user_config or default_config

如果 user_config 为假值(None、空字典),使用 default_config。

检查多个条件 ​

python
if x > 0 and x < 100 and x % 2 == 0:
    print("0-100 之间的偶数")

或链式比较:

python
if 0 < x < 100 and x % 2 == 0:
    print("0-100 之间的偶数")

避免重复计算 ​

利用短路:

python
if expensive_check() and another_check():
    pass
# 如果 expensive_check() 返回 False,another_check() 不执行

真值转布尔 ​

python
>>> bool([1, 2, 3])
True
>>> not not [1, 2, 3]  # 双重否定
True

推荐用 bool(),而非 not not。

练习 ​

  1. 预测输出:不运行代码,预测结果,然后验证:

    python
    print(0 or 5 or 10)
    print(10 and 20 and 0)
    print(not (5 > 3) or (2 < 1))
    print(1 < 2 < 3 < 4)
    print("" or [] or {} or 0 or "default")
  2. 短路验证:编写代码证明 and 和 or 的短路行为:

    python
    def side_effect():
        print("副作用发生")
        return True
    
    False and side_effect()  # 不打印
    True or side_effect()    # 不打印
  3. 真值判断:以下哪些为真?

    python
    bool([])
    bool([0])
    bool("")
    bool(" ")
    bool(0.0)
    bool(None)
  4. 优化条件:重写以下代码,使用链式比较和真值测试:

    python
    age = 25
    if age >= 18 and age <= 65:
        if name != "" and name is not None:
            print("有效用户")
  5. 三元表达式:用三元表达式实现:给定数字 x,返回其绝对值。

完成练习后,打开本章答案页核对。

下一步 ​

理解了运算符与真值逻辑,下一节深入数字类型:整数的任意精度、浮点精度陷阱、Decimal 精确计算。

回到第一章概览 · 返回Python 学习路线

用心记录每一步成长