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
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
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. 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:
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.
Here is a direct link to another table of operator precedence since I couldn't find one for the above.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With