Menu
CoddyTech

逻辑运算符第 4 部分

本课属于 Coddy Python 学习旅程的“基础知识”单元。第 19 课,共 77 课。

处理逻辑表达式时,有时我们需要简化或重新排列它们。处理由多个 and 和 or 运算符组合而成的复杂条件时,这一点尤其有用。

德摩根定律提供了转换逻辑表达式的规则。这些转换有助于让代码更易读、更容易理解。

第一定律:not (A and B) 与 (not A) or (not B) 相同

注意,将 not 分配到表达式中时会发生两件事:每个操作数都会被取反(A 变为 not A,B 变为 not B),并且运算符也会反转:and 变为 or。not 不只是对值取反,还会切换连接它们的运算符。

例如:

# 来看看一个数是否不在 1 到 10 之间。
number = 15
# 这两个表达式是等价的:
result1 = not (number >= 1 and number <= 10)
result2 = (not number >= 1) or (not number <= 10)
print(result1)  # True
print(result2)  # True

第二定律:not (A or B) 与 (not A) and (not B) 相同

这里同样适用两步规则:每个操作数都要取反,运算符也会翻转。这次,or 会变成 and。你可以这样理解:分配 not 时,and 和 or 总会互换,同时每个部分都要取反。

例如:

# 检查一个人是否既不是学生,也没有工作
is_student = False
is_employed = False
# 这两个表达式等价:
result1 = not (is_student or is_employed)
result2 = (not is_student) and (not is_employed)
print(result1)  # True
print(result2)  # True

同时使用 AND 和 OR 的复杂示例:有时,你需要组合使用这两个运算符来编写条件。来看一个实际示例:

# 检查是否不能接受求职申请
# 以下情况会拒绝申请:(没有工作经验且没有学位)或不符合年龄要求
has_experience = False
has_degree = False
meets_age = True
# 同时使用 AND 和 OR 的复杂条件
reject_application = (not has_experience and not has_degree) or not meets_age
print(reject_application)  # True(因没有工作经验且没有学位而被拒绝)
# 也可以用德摩根定律来写:
# accept = (experience OR degree) AND meets age; reject = not accept
accept_application = (has_experience or has_degree) and meets_age
reject_application2 = not accept_application
print(reject_application2)  # True(结果相同,逻辑不同)

何时使用德摩根定律:

  • 让否定条件更容易阅读
  • 简化复杂的逻辑表达式
  • 在同一逻辑的不同表示形式之间转换
challenge icon

挑战

入门

你正在帮助一家宠物店创建一个系统,用来判断是否可以向顾客出售宠物。

这些变量已为你设置好:

  • has_license 的值为 True
  • has_space 的值为 True
  • has_experience 的值为 False

编写逻辑表达式,判断以下情况:

  • can_sell_regular_pet:如果顾客有许可证或有经验,并且有足够的空间,就可以购买普通宠物
  • can_sell_exotic_pet:如果顾客既有许可证又有经验,并且有足够的空间,就可以购买珍奇宠物
  • cannot_sell_any_pet:如果顾客没有许可证,也没有经验,或者没有足够的空间,商店就不能出售任何宠物

亲手试试

# 计算条件
# 将下面的每个占位值替换为正确的逻辑表达式
can_sell_regular_pet = False
can_sell_exotic_pet = False
cannot_sell_any_pet = False

# 不要删除下面的代码行
print("Can sell regular pet:", can_sell_regular_pet)
print("Can sell exotic pet:", can_sell_exotic_pet)
print("Cannot sell any pet:", cannot_sell_any_pet)
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

基础知识中的所有课

自己练习: Python 在线编译器