1. 布尔类型的基本概念 #
bool只有两个值:True和False。- 用于条件判断和逻辑控制。
is_active = True
is_deleted = False
print(type(is_active)) # <class 'bool'>2. 逻辑运算 #
and、or、not用于组合布尔条件。
| 运算符 | 含义 | 示例 |
|---|---|---|
and |
两者都为真才为真 | a and b |
or |
任一为真则为真 | a or b |
not |
取反 | not a |
age = 20
has_ticket = True
print(age >= 18 and has_ticket) # True
print(age < 18 or has_ticket) # True
print(not has_ticket) # False2.1 短路求值 #
and左侧为假时不再算右侧;常用于避免空值报错。
user = None
# 先判断 user 存在,再访问属性
if user and user.is_active:
print("用户有效")or左侧为真时不再算右侧。`python def f(): print("右侧计算")
x = True if x or f(): print("左侧为真,右侧不计算")
x = False if x or f(): print(" 左侧为假,右侧计算")
## 3. 比较运算
- 比较结果是布尔值:`==`、`!=`、`>`、`<`、`>=`、`<=`。
```python
score = 85
print(score >= 60) # True
print(score == 100) # False4. 真值与假值 #
- 在
if、while等布尔上下文中,非布尔值也会当作真/假。 - 假值(Falsy):
False、None、0、0.0、""、[]、()、{}。 - 真值(Truthy):其余非空值一般为真。
name = ""
items = []
if name: # 空字符串为假
print("有名字")
if items: # 空列表为假
print("有数据")
else:
print("列表为空") # 会执行这里- 项目里常用
if data:判断「是否有内容」,比if len(data) > 0:更简洁。
5. 条件判断 #
if/elif/else按条件分支执行,适合处理状态、权限等多路判断。
status = "paid"
if status == "paid":
message = "已支付"
elif status == "pending":
message = "待支付"
else:
message = "未知状态"
print(message)6. any() 与 all() #
- 批量判断时很实用,例如校验表单多项是否通过。
fields = ["alice", "alice@example.com", "13800138000"]
all_filled = all(bool(f.strip()) for f in fields)
print(all_filled) # True
numbers = [2, 4, 6, 8]
all_even = all(n % 2 == 0 for n in numbers)
print(all_even) # Trueany(可迭代对象):有一个为真则返回Trueall(可迭代对象):全部为真才返回True
7. 项目开发要点 #
- 布尔变量命名:用
is_、has_、can_前缀,如is_admin、has_permission。 - 判断空值:优先
if not items:,不要写if items == []。 - 不要用
== True:直接写if is_active:,不要写if is_active == True:。 - 注意
True/False与1/0的关系:True == 1为真,但业务里应区分布尔与数字,不要混用算术。 - 复杂条件可拆变量:
can_edit = is_owner and not is_locked,提高可读性。 - 权限、校验:多个条件用
and/all()组合;满足其一用or/any()。