在'If'语句中执行'Or'操作的正确方法是什么? - Python

Har*_*vey 1 python

我有一个不符合我预期行为的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
Run Code Online (Sandbox Code Playgroud)

我的输入总是会导致userTime[-2]总是'Z'

打印userTime[-2].upper()到屏幕显示为"Z"但它仍然引发异常.

我无法理解else这个"如果"声明的部分,我现在想知道是否有一些我错过的东西

Kev*_*vin 6

相反的a or b是不是not a or not b,它是not a and not b.尝试:

if not userTime[-2].upper() == "X" and not userTime[-2].upper() == "Z":
Run Code Online (Sandbox Code Playgroud)

或者,等效地,

if userTime[-2].upper() != "X" and userTime[-2].upper() != "Z":
Run Code Online (Sandbox Code Playgroud)

或者,完全避免复杂布尔表达式的问题,

if userTime[-2].upper() not in ("X", "Z"):
Run Code Online (Sandbox Code Playgroud)

否定布尔表达式有点违反直觉.有关更多信息,请参阅De Morgan的法律.

  • 您可能希望使用`!=`而不是`not .. ==`. (3认同)
  • 应该有一个 - 最好只有一个 - 明显的方法来做到这一点.虽然这种方式起初可能并不明显,除非你是荷兰人. (2认同)
  • @AviahLaor:`if usertime [-2] .casefold()不在"xz"中:引发ValueError("未输入X或Z(忽略大小写)")`看起来很明显(对于读者来说). (2认同)