πLogical Operators, Seemingly Illogical Behavior
?!?!
And now an example that contains both and
and or
:
And this statement gets tricky to comprehend! Here's the core idea: the and
operator takes precedence over the or
operator.
In simpler English, what this means is that the statement looks something like this:
This statement first evaluates 1
, finds it to be a truthy value, and immediately returns it. This is why the 1/0
doesn't throw an error.
Try this one yourself:
Now that you've given this a shot, let's walk through it together!
First, the or
statement evaluates 0. Finding it to be a false-y value, it keeps going. It evaluates (None and 1/0)
next. In this, the and
finds None
to be the first false-y value, and immediately returns it. The outer or
statements sees None
as the next value, and keeps going. It therefore returns 2
, the first truth-y value it finds!
Last updated