布尔类型 #

布尔类型(bool)是Python中表示真假的数据类型,只有两个值:TrueFalse

一、布尔值 #

1.1 基本概念 #

python
# 布尔值
is_true = True
is_false = False

print(type(is_true))   # <class 'bool'>
print(is_true)         # True
print(is_false)        # False

1.2 布尔值的特点 #

python
# True 和 False 是关键字,首字母必须大写
# true, false 是错误的

# 布尔值是整数的子类
print(isinstance(True, int))   # True
print(isinstance(False, int))  # True

# True 等价于 1,False 等价于 0
print(True == 1)    # True
print(False == 0)   # True
print(True + 1)     # 2
print(False + 1)    # 1
print(True * 10)    # 10

1.3 布尔值的运算 #

python
# 算术运算
print(True + True)    # 2
print(True - False)   # 1
print(True * 5)       # 5
print(True / 2)       # 0.5

# 比较运算
print(True > False)   # True
print(True >= 1)      # True
print(False < 1)      # True

二、bool()函数 #

2.1 转换为布尔值 #

python
# 从其他类型转换
print(bool(1))        # True
print(bool(0))        # False
print(bool(-1))       # True(非零即为真)

print(bool(""))       # False(空字符串)
print(bool("Hello"))  # True(非空字符串)

print(bool([]))       # False(空列表)
print(bool([1, 2]))   # True(非空列表)

print(bool({}))       # False(空字典)
print(bool({"a": 1})) # True(非空字典)

print(bool(None))     # False

2.2 真假值规则 #

以下值转换为布尔值时为 False

python
# 假值(Falsy values)
bool(False)     # False
bool(None)      # False
bool(0)         # False
bool(0.0)       # False
bool(0j)        # False(复数零)
bool("")        # False(空字符串)
bool(())        # False(空元组)
bool([])        # False(空列表)
bool({})        # False(空字典)
bool(set())     # False(空集合)
bool(range(0))  # False(空range)

其他所有值转换为布尔值时为 True

python
# 真值(Truthy values)
bool(True)      # True
bool(1)         # True
bool(-1)        # True
bool(0.1)       # True
bool(" ")       # True(空格也是字符)
bool("False")   # True(非空字符串)
bool([0])       # True(非空列表)
bool([False])   # True(非空列表)
bool({0: 0})    # True(非空字典)

三、比较运算符 #

比较运算符返回布尔值。

3.1 相等比较 #

python
# 等于
print(5 == 5)        # True
print(5 == 6)        # False
print("hello" == "hello")  # True

# 不等于
print(5 != 6)        # True
print(5 != 5)        # False

3.2 大小比较 #

python
# 大于
print(5 > 3)         # True
print(5 > 5)         # False

# 小于
print(3 < 5)         # True
print(5 < 5)         # False

# 大于等于
print(5 >= 5)        # True
print(4 >= 5)        # False

# 小于等于
print(5 <= 5)        # True
print(6 <= 5)        # False

3.3 链式比较 #

python
x = 5

# 链式比较(Python特有)
print(1 < x < 10)    # True(等价于 1 < x and x < 10)
print(1 < x > 3)     # True
print(1 > x < 10)    # False

3.4 is 和 is not #

python
# 比较对象身份(是否同一对象)
a = [1, 2, 3]
b = [1, 2, 3]
c = a

print(a == b)        # True(值相等)
print(a is b)        # False(不是同一对象)
print(a is c)        # True(同一对象)

print(a is not b)    # True
print(a is not c)    # False

# None 的比较推荐使用 is
x = None
print(x is None)     # True(推荐)
print(x == None)     # True(不推荐)

3.5 in 和 not in #

python
# 检查成员
fruits = ["apple", "banana", "orange"]

print("apple" in fruits)      # True
print("grape" in fruits)      # False
print("grape" not in fruits)  # True

# 字符串中
print("ell" in "Hello")       # True
print("xyz" in "Hello")       # False

# 字典中(检查键)
person = {"name": "Tom", "age": 25}
print("name" in person)       # True
print("Tom" in person)        # False(值不在键中)

四、逻辑运算符 #

4.1 and 运算 #

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

# 短路求值
x = 0
# print(x > 0 and 10/x > 1)  # False(不会报错,因为第一个为假,不计算第二个)

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

4.2 or 运算 #

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

# 短路求值
x = 5
# print(x > 0 or 10/0 > 1)  # True(不会报错,第一个为真,不计算第二个)

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

4.3 not 运算 #

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

print(not 1)      # False
print(not 0)      # True
print(not "")     # True
print(not "hello") # False

4.4 运算优先级 #

python
# 优先级:not > and > or

# 等价于 True or (False and False)
print(True or False and False)  # True

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

# 使用括号明确优先级
print((True or False) and False)  # False

4.5 常用技巧 #

python
# 设置默认值
name = ""
display_name = name or "Anonymous"  # "Anonymous"

# 类似于JavaScript的 ||
value = 0
result = value or 10  # 10

# 条件赋值
x = 5
y = "positive" if x > 0 else "non-positive"

五、条件判断中的应用 #

5.1 if语句 #

python
is_valid = True

if is_valid:
    print("验证通过")

# 检查非空
name = "Tom"
if name:
    print(f"名字是:{name}")

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

# 检查None
data = None
if data is None:
    print("数据为空")

5.2 条件表达式 #

python
age = 18

# 三元表达式
status = "成年" if age >= 18 else "未成年"
print(status)  # "成年"

# 嵌套
score = 85
grade = "A" if score >= 90 else "B" if score >= 80 else "C"
print(grade)  # "B"

5.3 组合条件 #

python
age = 25
has_license = True

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

# 满足其中一个
day = "Saturday"
if day == "Saturday" or day == "Sunday":
    print("周末")

# 复杂条件
age = 25
income = 50000
credit_score = 700

if age >= 18 and income >= 30000 and credit_score >= 650:
    print("符合贷款条件")

六、布尔类型转换 #

6.1 显式转换 #

python
# 使用bool()
print(bool(1))          # True
print(bool(0))          # False
print(bool("hello"))    # True
print(bool(""))         # False
print(bool([1, 2]))     # True
print(bool([]))         # False

6.2 隐式转换 #

python
# 条件判断中自动转换
if "hello":
    print("非空字符串为真")

if []:
    print("这不会执行")
else:
    print("空列表为假")

# while循环
items = [1, 2, 3]
while items:
    print(items.pop())
# 输出:3, 2, 1

七、自定义类型的布尔值 #

7.1 __bool__方法 #

python
class Student:
    def __init__(self, name, scores):
        self.name = name
        self.scores = scores
    
    def __bool__(self):
        # 平均分及格则为真
        return sum(self.scores) / len(self.scores) >= 60

student1 = Student("Tom", [80, 75, 90])
student2 = Student("Jerry", [50, 55, 45])

print(bool(student1))  # True
print(bool(student2))  # False

if student1:
    print(f"{student1.name}及格了")

7.2 __len__方法 #

python
# 如果没有定义__bool__,会尝试调用__len__
class MyList:
    def __init__(self, items):
        self.items = items
    
    def __len__(self):
        return len(self.items)

my_list = MyList([1, 2, 3])
empty_list = MyList([])

print(bool(my_list))    # True(len > 0)
print(bool(empty_list)) # False(len == 0)

八、常见陷阱 #

8.1 与整数的比较 #

python
# True == 1, False == 0
print(True == 1)   # True
print(False == 0)  # True

# 但它们不是同一类型
print(True is 1)   # False

# 这可能导致意外
values = [1, 2, 3]
print(True in values)  # True(因为True == 1)

8.2 空容器的判断 #

python
# 空容器为假,但0和False不同
values = [0, False, None, "", [], {}, ()]

# 检查是否有假值
print(any(values))  # False(全为假)

# 检查是否全为假
print(all(values))  # False

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

8.3 字符串 “False” 是真值 #

python
# 字符串"False"是真值
x = "False"
if x:
    print("这是真值")  # 会执行

# 正确判断字符串布尔值
def str_to_bool(s):
    return s.lower() == "true"

print(str_to_bool("True"))   # True
print(str_to_bool("False"))  # False

九、总结 #

概念 要点
布尔值 TrueFalse,首字母大写
假值 False, None, 0, "", [], {}, ()
真值 除假值外的所有值
逻辑运算 and, or, not
比较运算 ==, !=, >, <, >=, <=, is, in
短路求值 and 遇假停止,or 遇真停止
运算符 表达式 结果
and True and True True
and True and False False
or True or False True
or False or False False
not not True False
not not False True
最后更新:2026-03-16