布尔值
一句话解释
布尔值 (bool) 是 类型 使用 two 值: 真 or 假, used for logic and 条件.
用大白话说
布尔值 represents truth — 它有 精确地 two 值: True and False (capitalized in Python). Booleans are used in if conditions, while loops, and logical operations.
Booleans result from comparisons (>, <, ==, !=, in, 是) and logical operators (and, or, 不). In Python, bool is a subclass of int — 真 is 1 and 假 is 0, so you can use them in arithmetic.
Python has the concept of truthy and falsy values. Falsy values are: 假, 0, 0.0, '', [], {}, 无. Everything else is truthy. This lets you write concise conditions like 如果 my_list: instead of 如果 len(my_list) > 0:.
示例
is_active = True
is_admin = False
print(is_active and is_admin) # False
print(is_active or is_admin) # True
print(not is_admin) # True
print(True + True) # 2 (bool is subclass of int)
# Truthy/falsy
if []:
print("empty list is truthy")
else:
print("empty list is falsy") # This prints布尔值 是 真/假, support logical 运算符, and 有 truthy/falsy 语义.
常见混淆
容易混淆的对象: integer
关键区别: bool 是 subclass 的 int in Python. 真 == 1 and 假 == 0. 但 布尔值 represent logical truth, 虽然 integers represent 数量. Use bool() 到 convert 任何 值 到 它的 truthy/falsy 布尔值.
相关术语
相关资源
相关课程
- 数据 类型
布尔值 类型.
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。