Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我写了这段代码(在这个范围之前x运行):str()
x
str()
if x == "A" or "O": return x
这在B时返回x = B。有人可以帮我理解为什么x = B在这里验证吗?
B
x = B
当我将代码更改为阅读时
if x == "A": return x elif x == "O": return x
它不匹配x = B,所以我假设这里有一些我不理解的布尔逻辑。
if x == "A" or "O":应该是if x == "A" or x == "O":。
if x == "A" or "O":
if x == "A" or x == "O":
if x == "A" or "O":将始终评估为true.
true
if x == "A" or "O":被解释为:
if (x == "A") or ("O"),"O"是true,所以即使x不是"A",既然你有or,这将永远是true。
if (x == "A") or ("O")
"O"
"A"
or
或者,您可以编写:
if x in ["A", "O"]: