Using or With Common Objects
Let me go back and take a look at the last slide from your last lesson. I want to phrase this observation in a slightly different way. If I’m taking the
<exp1> or <exp2> and
True, the result of the
or operation is
Now, in this lesson, we’re going to take a look at how you can use the
or operation with common objects in Python. Python allows you to use the word
or with things other than Boolean expressions.
Some things that you need to know: All objects in Python have a truth value and most of them are
True. A few of them are
False. Items that have values of the keyword
False are considered
False, numbers of any type that have a value of
0 will be considered
False, and empty collections—strings, sequences, tuples, et cetera—all of those evaluate to
And if you have a class that implements a method
.__bool__() that returns
False or has a method
.__len__() which returns
0 for an object, then that object also will evaluate to
False. But otherwise, an object is going to evaluate to
When you use the
or operator in Python between non-Boolean expressions, the result is going to be one of the two expressions. It doesn’t convert everything and return a
False, which some other languages do.
If you perform an
or between two objects in Python, the result will be one of those two objects, and the rule is the same as the last observation that I made: If the first object evaluates to be
or operation returns the first object.
Become a Member to join the conversation.