For more information on topics covered in this lesson, check out these resources:
Returning Expressions With Boolean Operators
Here are some examples, and we’ll look through these one at a time.
0 and 1.
0 is falsy,
1 is truthy, so this is going to evaluate to something falsy, but it doesn’t evaluate to the word
False. It evaluates to
True, but Python tells us
1. What’s happening here? In evaluating an expression with
and, Python returns the first falsy value it finds or the value of the last operand if all of the ones preceding it were truthy.
or returns the first truthy value it finds or the value of the last operand if all of the preceding ones were falsy. So a simple function to return the value of
a and b won’t always be a value of
If I have this function that wants to tell me if
b are both
True and I use it simply returning a Boolean expression, I ask it to tell me if
2 are both
True—it doesn’t say “Yes,
True” or “No,
False,” it tells me
That’s not useful. There are several ways that you can fix this, and we’ll take a look at three of them. First, we can explicitly use an
if statement and
return statements that return the values
Another way is to use Python’s ternary operator. This is a three-part statement with an
if condition, a value to return if the condition is
True, which comes before the word
if, and a value to return if the condition is
False, which comes after the word
You can see the Real Python article on Python’s ternary operator for more information on how this operator is used. In our case, we’re simply repeating the logic of our previous version of the function using the ternary operator. If
a and b evaluates to a truthy value, we return
False. Remember, many times we can simply put a Boolean expression as the return value for our function that we want to return a value of
False, but if the Boolean expression involves
or, we’ll probably need to use one of these three variations.
Become a Member to join the conversation.