Member-only story
Boolean Operators in Python Aren’t What You Think
There’s more to these little guys than meets the eye
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.
And why wouldn’t I think this? After all, we’ve been using if
statements forever and they’ve never disappointed.
if 1 and 0:
print("You will never see this...")
if 1 or 0:
print("But this you will see!")
Obviously, 1 and 0
is equivalent to False
and 1 or 0
to True
, right?
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…