我有这行简单的代码:
i = " "
if i != "" or i != " ":
print("Something")
这应该很简单,如果 i 不是空 ""
或者它不是空格 ""
,但它是,则打印 Something。现在,如果这两个条件之一为 False
,为什么我会看到打印出的东西?
最佳答案
"not (A and B)" is the same as "(not A) or (not B)"
also,
"not (A or B)" is the same as "(not A) and (not B)".
就您而言,根据第一个陈述,您已经有效地编写了
if not (i == "" and i == " "):
这是不可能发生的。因此,无论输入是什么,(i == ""and i == "")
将始终返回 False
,对其求反将给出 True
总是。
相反,你应该这样写
if i != "" and i != " ":
或者根据德摩根定律引用的第二个陈述,
if not (i == "" or i == " "):
关于Python And Or 语句的行为..很奇怪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35496768/