我有这行简单的代码:
i = " " if i != "" or i != " ": print("Something")
这应该很简单,如果 i 不为空""或不是空格" ",但实际上为空,则打印 Something。现在,为什么如果这两个条件之一为 ,则会看到 Something 被打印出来False?
""
" "
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。
(i == "" and i == " ")
True
相反,你应该这样写
if i != "" and i != " ":
或者根据德摩根定律的第二条陈述,
if not (i == "" or i == " "):