Non-Boolean Contexts
00:00
We’ve just seen how we can use the or
operator with Boolean expressions to control things like if
statements and while
loops. However, because Python can also perform or
operations on things that aren’t Boolean expressions, there are some new opportunities that we have for writing code to take advantage of that.
00:21
One is just simply the assignment of variables to a possibility of values in the event that one or more values might not exist. So, for example, suppose that I have two variables a
and b
, and normally I want something to be assigned to a
, but in the event a
doesn’t contain anything meaningful, I want it to be assigned to b
.
00:45
So I could say something like var1 = a or b
. If a
has a meaningful value, it’ll be assigned to var1
. If not, we’ll assign b
’s value to var1
.
01:00
If we change this up a little bit and say that a
doesn’t have a value and b
still does—
01:09
create a new variable, var2 = a or b
—we will see now that var2
has the value of 2
.
01:20
That’s one of the ways that you’re going to see in these next examples of how we use the word or
. The first possibility might be what we’re ideally looking for and the second one provides a backup value in the event that the first one doesn’t contain something meaningful for us to use.
01:38
So, let’s take a look at some more examples of using the or
in a non-Boolean expression.
Become a Member to join the conversation.