我有一个不符合我预期行为的If staement。
以下是我的例子:
if not userTime[-2].upper() == "X" or not userTime[-2].upper() == "Z":
raise ValueError("not entered an X or a Z")
else:
notValid = False
我的输入总是导致userTime[-2]
始终是大写'Z'
将userTime[-2].upper()
打印到屏幕显示为“Z”但它仍然会引发异常。
我无法理解这个'如果'声明的else
部分,我现在想知道是否有一些我错过了
答案 0 :(得分:6)
a or b
的反面不是{{1}},而是not a or not b
。尝试:
not a and not b
或者,相当于
if not userTime[-2].upper() == "X" and not userTime[-2].upper() == "Z":
或者,完全避免出现复杂的布尔表达式,
if userTime[-2].upper() != "X" and userTime[-2].upper() != "Z":
否定布尔表达式有点违反直觉。有关详细信息,请参阅De Morgan's laws。