πLogical Operators, Seemingly Illogical Behavior
?!?!
And now an example that contains both and
and or
:
>>> 1 or 0 and 1/0 or 2
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:
>>> 1 or (0 and 1/0) or 2
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:
>>> 0 or None and 1/0 or 2
Now that you've given this a shot, let's walk through it together!
>>> 0 or None and 1/0 or 2
>>> 0 or (None and 1/0) or 2
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
Was this helpful?