If you’d like to learn more about Boolean operators and short-circuit evaluation, then check out the following:
Using not With Other Boolean Operators
Specifically, Boolean operators have a lower precedence than comparison operators. That means comparisons will be done first, before things like
or. So for an example, in an expression like
not True == False, the comparison will be done first.
True does not equal
False, so the comparison is
Now this expression probably makes sense to you.
not True, so would expect this to be
True. But this actually gives an error, which you can see at the bottom of the screen. What’s happening?
01:56 This way gives the intended result. Why is this important to know? Because many times, you’ll want to connect comparisons with Boolean operators, and you need to understand how Python will evaluate them.
Also note, when mixed with other Boolean operators,
not has the highest precedence, followed by
and and then
or. Another thing to keep in mind, the result of the
not operation is always
But if you’re familiar with the other Boolean operators, perhaps you know that’s not always the case with
or. It is true that often the result of
False, as these examples show, but Python uses something called short-circuit evaluation.
And the way it does this means the result of an
or operation could be one of the operands. So in an expression like
0 and 42, Python will note that the first operand is false and provide that as the result.
But if you use
or instead, Python again noticing that
0 is false, that means for
or, the result is whatever the second operand is—in this case,
42. So even though the results for
or can be any number of things, that is not the case for
Become a Member to join the conversation.