逻辑运算符(第 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 的复杂示例:有时你需要结合这两个运算符的条件。这里有一个实际示例:
# 检查我们是否无法接受求职申请
# 以下情况拒绝:(没有经验 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(因没有经验 AND 没有学位而被拒绝)# 这也可以使用德摩根定律(De Morgan's Laws)来写:
# 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(结果相同,逻辑不同)混合使用 and 和 or:Python 会先计算 and 再计算 or,就像乘法优先于加法一样。缺少括号可能会改变结果:
print(True or False and False) # True:这意味着 True or (False and False)
print((True or False) and False) # False:先计算 or 部分当条件表达为“A 或 B,并且还需要 C”时,请在 or 部分加上括号:(a or b) and c。
何时使用德摩根定律:
- 使否定条件更容易阅读
- 简化复杂的逻辑表达式
- 在同一逻辑的不同表示形式之间进行转换
挑战
入门你正在帮助一家宠物店创建一个系统,用于判断他们是否可以向顾客出售宠物。
以下变量已经为你设置好:
has_license值为Truehas_space值为Truehas_experience值为False
编写逻辑表达式来确定以下情况:
can_sell_regular_pet:如果顾客拥有许可证或经验之一,并且拥有空间,则可以购买普通宠物can_sell_exotic_pet:如果顾客同时拥有许可证和经验,并且拥有空间,则可以购买异宠cannot_sell_any_pet:如果顾客既没有许可证也没有经验,或者没有空间,则店家不能出售任何宠物
系统还会使用这 3 个变量的其他值来检查你的表达式,因此请基于变量来构建每一个表达式,而不是基于上面的具体值。
亲手试试
# 计算条件
# 将下方每个占位符的值替换为正确的逻辑表达式
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)
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
基础知识中的所有课
自己练习: Python 在线编译器