I consider myself a decent Python programmer. I’ve worked with the language extensively in the past and it’s the one I generally feel most comfort

Boolean Operators in Python Aren’t What You Think

submited by
Style Pass
2021-06-05 05:30:09

I consider myself a decent Python programmer. I’ve worked with the language extensively in the past and it’s the one I generally feel most comfortable using.

But even well within the cozy confines of our comfort zones, every now and then, we all come across energizingly unfamiliar “huh” moments. Recently, I had one such moment and it came from where one might least expect it: good old Boolean operators.

You see, until that point, I was under the impression that the expressions True and False, "abc" and "", and None or 0 would all evaluate to False, owing to the fact that Python interprets False, None, empty strings, numeric zero of all types, as well as other values as false.

But here’s the catch: The fact that Python interprets certain non-Boolean values (like 1 or "") as True or False when presented in a Boolean context (e.g. when used in conjunction with a Boolean operator) says nothing about the return value of said context. In other words, what does val = True and 1 evaluate to?

It turns out Boolean operations return the value of the last evaluated argument. In the case of and, the expression short-circuits as soon as a non-true (true in the case of or) value is encountered. Otherwise, the truth value of all arguments needs to be checked.

Leave a Comment