我有以下简单的代码行:
i = " " if i != "" or i != " ": print("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 != " ":
或根据De Morgan引用的第二条陈述,
if not (i == "" or i == " "):