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

2024-06-17 10:05:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个“如果”站,它的行为不符合我的预期。你知道吗

下面是我的例子:

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”,但仍会引发异常。你知道吗

我不能让它击中这个'if'语句的else部分,现在想知道我是否遗漏了什么


Tags: oranfalseif屏幕notupperelse
1条回答
网友
1楼 · 发布于 2024-06-17 10:05:03

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":

或者,等价地

if userTime[-2].upper() != "X" and userTime[-2].upper() != "Z":

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

if userTime[-2].upper() not in ("X", "Z"):

否定布尔表达式有点违反直觉。有关详细信息,请参阅De Morgan's laws。你知道吗

相关问题 更多 >