[英]How to make an OR statement in python?
Why does this not work: 为什么这不起作用:
file = "v3a2"
if "v1" or "v2" in file:
v1.write(total)
elif "v3" in file:
print "never here?????"
How to formulate this? 如何制定这个?
if "v1" or "v2" in file:
is equivalent to 相当于
if ("v1") or ("v2" in file):
Which will always be True
because bool("v1")==True
这将永远是True
,因为bool("v1")==True
you could say 你可以说
if any(x in file for x in ["v1", "v2"]):
or 要么
if "v1" in file or "v2" in file:
The version with any
looks nicer if there are more than 2 or 3 items to check 如果要检查的项目超过2个或3个,那么any
看起来更好的版本
Try 尝试
if "v1" in file or "v2" in file:
instead of 代替
if "v1" or "v2" in file:
Perhaps a review of Python Boolean Operations might be helpful. 也许对Python 布尔运算的回顾可能会有所帮助。 At the bottom of that page in the summary there is also a table of operator precedence . 在摘要中该页面的底部还有一个运算符优先级表 。 If you consult you the table, you can see that since the in
operator has a higher precedence than or
operator, the expression is interpreted like this: 如果您向表格咨询,您可以看到由于in
运算符的优先级高于or
运算符,表达式的解释如下:
if ("v1") or ("v2" in file):
rather than what you expected/intended. 而不是你的期望/意图。
Also note that, as @sepp2k mentions in a helpful comment below, that if or
had a higher precedence than in
, your expression would end up as if ("v1" or "v2") in file:
which also would not work the way you intended. 还要注意,正如@ sepp2k在下面的一个有用的评论中提到的那样,如果or
有一个比in
更高的优先级,你的表达式最终会像文件中的那样if ("v1" or "v2") in file:
这也不会起作用你打算。
Here is a direct link to another table of operator precedence since I couldn't find one for the above. 这是到另一个运算符优先级表的直接链接,因为我找不到上面的那个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.