1. 布尔类型的基本概念 #

is_active = True
is_deleted = False

print(type(is_active))   # <class 'bool'>

2. 逻辑运算 #

运算符 含义 示例
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)             # False

2.1 短路求值 #

user = None
# 先判断 user 存在,再访问属性
if user and user.is_active:
    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)       # False

4. 真值与假值 #

name = ""
items = []

if name:          # 空字符串为假
    print("有名字")

if items:         # 空列表为假
    print("有数据")
else:
    print("列表为空")   # 会执行这里

5. 条件判断 #

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)     # True

7. 项目开发要点 #