Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make an OR statement in python?

Tags:

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?

like image 342
jorrebor Avatar asked Dec 02 '22 21:12

jorrebor


2 Answers

        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

like image 60
John La Rooy Avatar answered Dec 07 '22 22:12

John La Rooy


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.

like image 35
Levon Avatar answered Dec 07 '22 23:12

Levon