导航菜单

  • 1.Python介绍
  • 2.Python解释器
  • 3.安装Python
  • 4.VSCode开发Python
  • 5.print
  • 6.进制
  • 7.编码
  • 8.Unicode2UTF8
  • 9.整数类型
  • 10.字符串类型
  • 11.布尔类型
  • 12.变量与内存
  • 13.浮点类型
  • 14.注释
  • 15.if条件
  • 16.while循环
  • 17.运算符
  • 18.输入
  • 19.列表
  • 20.元组
  • 21.集合
  • 22.字典
  • 23.for循环
  • 11.1 布尔类型的基本概念
  • 11.2 逻辑运算
    • 11.2.1 短路求值
  • 11.3 比较运算
  • 11.4 真值与假值
  • 11.5 条件判断
  • 11.6 any() 与 all()
  • 11.7 项目开发要点

11.1 布尔类型的基本概念 #

bool 只有两个值:True 和 False,用于条件判断和逻辑控制。

is_active = True
is_deleted = False

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

11.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

11.2.1 短路求值 #

and 左侧为假时不再算右侧;常用于避免空值报错:

user = None
# 先判断 user 存在,再访问属性
if user and user.is_active:
    print("用户有效")

or 左侧为真时不再算右侧。

def f():
    print("右侧计算")

x = True
if  x or f():
    print("左侧为真,右侧不计算")

x = False
if x or f():
    print(" 左侧为假,右侧计算")

11.3 比较运算 #

比较结果是布尔值:==、!=、>、<、>=、<=。

score = 85
print(score >= 60)        # True
print(score == 100)       # False

11.4 真值与假值 #

在 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: 更简洁。

11.5 条件判断 #

status = "paid"

if status == "paid":
    message = "已支付"
elif status == "pending":
    message = "待支付"
else:
    message = "未知状态"

print(message)

11.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
  • any(可迭代对象):有一个为真则返回 True
  • all(可迭代对象):全部为真才返回 True

11.7 项目开发要点 #

  1. 布尔变量命名:用 is_、has_、can_ 前缀,如 is_admin、has_permission
  2. 判断空值:优先 if not items:,不要写 if items == []
  3. 不要用 == True:直接写 if is_active:,不要写 if is_active == True:
  4. 注意 True/False 与 1/0 的关系:True == 1 为真,但业务里应区分布尔与数字,不要混用算术
  5. 复杂条件可拆变量:can_edit = is_owner and not is_locked,提高可读性
  6. 权限、校验:多个条件用 and/all() 组合;满足其一用 or/any()
← 上一节 10.字符串类型 下一节 12.变量与内存 →

访问验证

请输入访问令牌

Token不正确,请重新输入