Python中if取反语句不符合预期的原因及德摩根定律应用讲解
if多条件反向判断逻辑错误详解
我是编程新手,已经理解基础if语句的用法,但对下述代码的逻辑有疑问,希望有人能通俗讲解其出错原因:
前置代码
import argparse parser = argparse.ArgumentParser() parser.add_argument("mode", help="Use encode/decode") args = parser.parse_args() mode = args.mode encode = 'encode' decode = 'decode'
正向逻辑(运行正常)
我首先写了正向判断支持模式的逻辑,运行无问题:
if mode == encode or mode == decode: print("Mode is supported!")
我想要实现上述逻辑的反向判断:如果mode不是支持的类型,就报错退出。
正常运行的反向写法
搜索后我写出了下面这组可正常运行的代码:
if not (mode == encode or mode == decode): print("Mode isn't supported") exit()
疑问:错误的反向写法问题出在哪?
我最开始自己写的下面这组代码,完全达不到反向判断的效果,想知道原因:
if mode != encode or mode != decode: print("Mode is encode or decode) exit()
逻辑梳理(解答)
很多人建议我学习德摩根定律(De Morgan's Law),我写了测试代码验证后彻底搞懂了逻辑,整理如下:
原正向逻辑的运行结果
if mode == encode or mode == decode: print("Mode is supported")
- 当mode = encode:
True or False = True,进入分支打印提示 - 当mode = decode:
False or True = True,进入分支打印提示 - 当mode = test(非法值):
False or False = False,不进入分支
错误写法的运行结果
if mode != encode or mode != decode: print("Mode isn't encode or decode") exit()
- 当mode = encode:
False or True = True,触发退出,合法值被误判 - 当mode = decode:
True or False = True,触发退出,合法值被误判 - 当mode = test(非法值):
True or True = True,触发退出
可以看到不管输入什么值,这个判断都会触发退出,完全不符合预期。核心原因是or逻辑只要有一个条件成立整体就成立,对于合法的mode来说,它必然不等于另外一个值,所以判断永远为真。
正确反向写法1(整体取反)
if not (mode == encode or mode == decode): print("Mode isn't encode or decode") exit()
- 当mode = encode:
(True or False) = True→not(True) = False,不触发退出 - 当mode = decode:
(False or True) = True→not(True) = False,不触发退出 - 当mode = test(非法值):
(False or False) = False→not(False) = True,触发退出
符合需求,是正向逻辑的正确反向。
正确反向写法2(拆分取反+逻辑符替换)
根据德摩根定律,对A or B取反等价于(not A) and (not B),所以也可以写成下面的形式,运行效果完全一致:
if mode != encode and mode != decode: print("Mode isn't encode or decode") exit()
- 当mode = encode:
False and True = False,不触发退出 - 当mode = decode:
True and False = False,不触发退出 - 当mode = test(非法值):
True and True = True,触发退出
以上梳理的推导过程也适用于其他多条件的反向判断场景,希望能帮到其他入门的编程新手。
内容的提问来源于stack exchange,提问作者volitank
相关产品推荐
相关产品推荐

