# Python: logical operations with None and Booleans

Coming back to the blog after long break.

Today, almost by accident I found how logical operators work with `None` in Python. The result is surprising, because it is not commutative.

```(False or None)  is None
(None  or False) is False
(True  or None)  is True
(None  or True)  is True

(False and None)  is False
(None  and False) is None
(True  and None)  is None
(None  and True)  is None
```

There seems to be little logic here (pun intended), but in fact it all makes sense. For “or”, if the first operand is truthy, it is returned, and the second operand is not calculated. If the first operant is falsy, the second operand is returned. For “and”, if the first operand is falsy, it is returned, and if it is truthy, the second operand is returned. The definitions are not symmetrical, which results in non-commutative behavior with `None`.

UPDATE: Javascript behaves the same way with `null>`. E.g. `(null && false) === null`, but `(false && null) === false`.

1. You are absolutely correct about short circuit. But historically, it was invented as an optimization technique, and later reused as a tool to prevent unwanted side effects [ if (p && p->data > 10) ], so one subconciously expects “or” to still be commutative if the operands are simple constants. I think this is still true in C, C++, Java and C#. But I Just checked Javascript, and guess what? It behaves like Python ðŸ™‚