Search code examples
pythonlogical-operatorsboolean-logicshort-circuiting

Question about short circuiting with python logical operators


According to short circuit rules, any time we have a True or ... statement it returns True, regardless of the rest of the statement. e.g., even if the rest of the statement throws an error, it would return True. Similarly, False and ... statement always returns False. I have also found this explanation online to sum it up.

So, when I tried to run this:

a = False or (5>"hello")
print(a)  

I had a TypeError because '>' is not supported between str and int.

b = True or (5>"hello")
print(b)

This one, however, prints True and it proves the short circuit rule. I did the same by applying for False and ... here:

c = False and (5>"hello")
print(c)

and this one prints False as expected.

So far, we have showcased the concept of short circuiting. But here is the problem:

d = False and False or True
print(d)

e = True or False and False
print(e)

If you run the code above, you would see that both d and e are True. Although we have a False and ... statement at the beginning for d, it seems to run the entire statement without short circuiting. So: False and False -> False, False or True -> True. Here I thought "Hm, ok. Maybe it is because I had 3 booleans". But when it came down to e the program seems to have a short circuit because if it hasn't, the result must have been: True or False -> True, True and False -> False.

Could you please explain why the program is short circuiting by e but not by d?


Solution

  • and has a higher precedence than or, so your code is equivalent to this:

    d = (False and False) or True
    print(d)
    
    e = True or (False and False)
    print(e)
    

    For it to work like you expect, you have to change d to this:

    d = False and (False or True)