The not Operator
First of all, a Boolean operator takes as input one or more Booleans and returns a Boolean. It’s convenient to completely specify a Boolean operator using what’s called the truth table, and we’ll do so for the three Boolean operators that we’ll focus on. In the mathematical theory of Boolean algebra, the three operators
or play an important role.
All right, let’s start off with the
not operator. The
not operator is the only unary Boolean operator implemented in Python. Unary is just a fancy word meaning that the operator takes only one input. In Python, to apply the
not operator on the input
x, you simply type
not can be applied to any object, not just Boolean data types.
not always returns either
False, depending on the Boolean value of the input. Now, I mention this because
not is the only Boolean operator that we’ll discuss that always returns a Boolean data type.
All right, let’s try out how the
not operator works on just some basic objects. So,
not True, as we saw, will return
not False will return
True. We can also apply
not to integers, so
not 1 returns
Whereas if you were to try
not with the empty string, you’re going to get
True. You can interpret this as meaning that the empty string has a Boolean value of
False. Let’s try this, say, on a list.
So, for example, let’s suppose that you have a field in either a database or maybe the input in some form, and it’s supposed to contain the first name of a user, and the user didn’t pass in a first name and so
first_name is an empty string.
You could do this using an
if not first_name. In this case, if
first_name is an empty string, it will have a Boolean value of
not False is
True, so we’ll enter into the
And then maybe what you want to do is set the
first_name string to, say, something like
"Not given". The idea is going to be that if
first_name is an empty string, then you’re going to display somewhere that the first name wasn’t given.
On the other hand, if
first_name does have a non-empty value—so, for example,
"Luigi"—in this case, our
if condition in the
not first_name will return a value of
False because a non-empty string has a Boolean value of
not True returns
Now, you could do this a little bit faster using the ternary operator in Python. For example, in the case where you have an empty string, you could do something like
first_name, we’ll set it equal to
"Not given" if the user did not pass a first name.
And so in this case, we’ll say
"Not given" if not first_name, otherwise
first_name should just stay as the value that was passed in by the user, so we’ll return
first_name. So in this case, because the string
first_name was empty, it’s going to be assigned a value of
in this case, when we use the ternary operator, the
not first_name returns a value of
False because in this case
first_name is a non-empty string, and so this condition after the
if statement is
Become a Member to join the conversation.