Using Python's and Operator With Common Objects
00:00
In this lesson, you’ll learn that and
can be used with more general objects than Boolean expressions and see how that evaluation is performed.
00:09
and
can be used with Python objects because all objects in Python have a truth value. Most objects are True
, but there are some exceptions.
00:18
Thee None
object and False
, of course, are False
. Any numeric type with a value of zero is False
, and empty collections like lists, strings, and so on are also considered False
. Also, if a class has certain dunder methods, like say .__len__()
or .__bool__
, then what they return, like a length of zero, would determine if that object were False
. So Python objects can be connected with the word and
since they all have some truthiness to them.
00:51
When and
is performed on objects, the value returned is one of those objects. The result isn’t going to be True
or False
.
01:01
This makes Python’s implementation a little different than other languages that let you perform and
with things other than just Boolean expressions.
01:10
If the first operand is False
, then that object will be the result of the operation. Remember how I phrased something in an earlier lesson? If the first operaand is False
, that’s what’s returned—that meaning the first operand.
01:26
If the first operand is True
, then the second operand object is the result of the operation. As you heard me say earlier, I carefully phrased these results in this manner before so that it would match up with a more general case you’re learning now. So in your program, if you have two objects, x
and y
, and you’re taking the and
of them, the result will be x
if x
is False
and y
if x
is True
.
01:53
And again, this is basically a generalization of what you’ve learned before. Let’s take a look at some examples. 2 and 3
. This makes perfect sense in Python.
02:07
And since 2
is considered true, the result of the operation should be the second operand, 3
. Another one with numbers: 5
and 0.0
.
02:19
Since 5
is also true, the second operand, 0.0
, will be the result.
02:26
In this case, the first operand is an empty list. That evaluates to False
, so that operand, the empty list, should be the result. And it is.
02:39
Here, 0
is considered false, so that will be the result. And one more case. False
is, of course, false, so that will be the result.
02:55
Next, you’ll learn how to mix Boolean expressions and objects using and
.
Become a Member to join the conversation.