Using or With Common Objects
00:00
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 or
of <exp1> or <exp2>
and exp1
is True
, the result of the or
operation is exp1
.
00:21
True
in both cases, exp1
is the result. If exp1
is False
, then the result is exp2
, whatever exp2
’s value was.
00:38
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.
00:55
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 None
or 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 False
.
01:23
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 True
.
01:42
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 True
or False
, which some other languages do.
01:59
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 True
, the or
operation returns the first object.
02:20
If the first object evaluates to be False
, the or
operation returns the second object.
02:29
And so with that in mind, we can actually perform or
operations on things that aren’t Boolean expressions. So, for example, I can take the or
of 3 or 7
.
02:44
3
is True
, and so we know the or
operation is going to give us the first object, which is 3
.
02:52
If I say empty string, "" or 19
, here we have the first operand is False
, and so we get back the second operand.
03:06
If I have an empty list or an empty tuple, because the first expression is False
, I get the second expression back.
03:18
Let’s see, which case haven’t I done? I’ve not done where the first one is True
, 18
, or the second one is False
. We get the first one back.
03:31
So again, an object can have a truth value associated with it. If we use objects in an or
expression, then if the first object evaluates to be True
, we get the first object.
03:44
If the first object evaluates to be False
, we get the second object.
03:50
In your next lesson, we will take a look at what happens when you mix Boolean expressions with objects in an or
statement.
Become a Member to join the conversation.