Search code examples
pythonbooleanshort-circuitingtruthtable

Python: How to chain boolean tests to get False as soon as it gets the first False


After having a lot of trouble trying to reduce nested ifs (and a script that stopped working), I realized perhaps I am having the wrong idea of what and how boolean stuff works in python.

I had this (working fine but contorted):

if (not gotside):
    if (j > 1):
        if (j < a.shape[1] - 1):
            if a[i, j+unit]:
                print "only now I do stuff!"

And tried this (looking sreamlined by not working as desired):

if (not gotside) and (j > 1) and (j < a.shape[1] - 1) and a[i, j+unit]:
    print "I'm well tested but not so indented..."

Then I tried to use "or" instead of "and", but didn' work, because (later I found) when you use x and y or even x or y you get one of x, y, and not one of True, False, acording to docs.

So, I don't know how I can put a handful of tests one after another (preferrably in the same line, with boolean operators) in a way that the whole expression returns False as soon as the first test evaluates to False.

Thanks for reading!


Solution

  • Your example should work.

    if x and y and z:
        ...
    

    Should happen only if none of x, y and z evaluate to False, and in Python, and short-circuits, so will return the False value as soon as one item fails. We can show this quite easily:

    >>> def test(n):
    ...     print("test", n)
    ...     return n
    ... 
    >>> test(1) and test(2)
    test 1
    test 2
    2
    >>> test(0) and test(2)
    test 0
    0
    >>> test(0) and test(2) and test(3)
    test 0
    0
    >>> test(1) and test(0) and test(3)
    test 1
    test 0
    0