Using and in Non-Boolean Contexts
00:00
In this lesson, you’ll see how to use an and
operation separate from any if
statement or while
loop condition. Consider this small code segment.
00:11
The purpose of this code is to assign a Boolean value to the variable flag
to tell a part of the program further along whether or not some condition was true.
00:22
It’s anticipated that this variable will be used in some other if
or while
statement, but right now you’re only concerned with how it gets assigned.
00:31
There are two conditions which need to be true for this variable to be assigned True
.
00:37
The list in question must have at least one element in it. In other words, it can’t be empty. And the first element must contain the string "expected value"
.
00:47
If those two conditions are true, then you want to set the flag
variable to True
. Otherwise, it will retain its previously assigned value of False
.
00:58
However, you don’t need to use an if
statement to make this happen. You simply want flag
to be the result, True
or False
of the and
operation.
01:09 So you should write your code in just that way.
01:13
flag
will be set to the truth value of length of the list is greater than 0
and element 0
has the string "expected value"
. If both conditions are true, then flag
will have the value True
. If either of those conditions are false, then flag
will be False
. Exactly what you wanted.
01:34 Observe also how this statement is taking advantage of short-circuit evaluation. The second expression will actually cause an error if the list is empty.
01:45
However, you test for that in the first expression. If the list is empty, then that part of the and
expression is false, and Python knows the whole expression evaluates to False
without needing to check the second expression.
02:01 So Python will only check the second expression if the first expression is true, meaning the list is not empty, and a check for the first element in the list won’t cause a program error.
02:14 This is an excellent use of short-circuit evaluation, so you should be sure to recall this in your own programs as needed.
02:23
Next, you’ll see more examples of using the and
operator.
Become a Member to join the conversation.