Search code examples
pythonlistboolean-logicnested-if

nested "and/or" if statements


I am working on code which creates a list and then applies both the "or" and "and" conditions to do further action:

a= ["john", "carlos", "22", "70"]

if (("qjohn" or "carlos") in a) and (("272" or "70") in a):
    print "true"
else:
    print "not true"

output:

not true

when I do this:

a= ["john", "carlos", "22", "70"]

if ("qjohn" or "cdarlos" in a) and ("272" or "d70" in a):
    print "true"
else:
    print "not true"

output is "true"

What I am not getting is **carlos and 70** should be equal to true but it's printing "not true". What is the cause of this error? Thanks


Solution

  • Both approaches are incorrect. Keep in mind or is a short-circuit operator so it's not doing what you think it does:

    it only evaluates the second argument if the first one is false.

    However, non-empty strings are always True, so that the first case only checks for the containment of the first non-empty string while the second never performs the containment check with in at all, therefore, it is always True.

    What you want is:

    if ("qjohn" in a or "carlos" in a) and ("272"  in a or "70" in a):
       ...
    

    If the items to test were longer, you could avoid repeating the or by using any which like or also short-circuits once one of the items test True:

    if any(x in a for x in case1) and any(x in a for x in case2):
       ...