Other Boolean Operators
Files associated with this lesson:
Other Boolean Operators.ipynb
Other Boolean Operators¶
In this category we'll place a few other operators that are incredibly useful for boolean operations and comparisons.
Membership Operator (in
)¶
Check if a given "object" is part of another "object". Examples:
print('e' in "Hello World")
print('l' in "Hello World")
print('x' in "Hello World")
Is Operator - Warning!¶
This operator is incredibly useful and provides a nice english-like syntax when used to compare objects. But you should be careful when using it. As a general rule, use it only with booleans (True
, False
) or None
. Examples:
x = None
print(x is None)
active = True
print(active is True)
closed = False
print(closed is False)
We could have used the equals (==
) operator for the previous examples, but is
just reads better. What do you think? Which one looks better?
if active == True:
pass
if active is True:
pass
I personally think that "active is True** reads better (pretty much like english). Although, to be more concise, in that case we could just have used, which provides the same outcome:
if active:
pass
Negation operator (not
)¶
This operator will just flip the current boolean value passed. Examples:
print(not True)
print(not False)
As you can see, the values are just inverted. This is related to Boolean Algebra if you're interested in learning about the details. We prefer to take a more "pragmatic" approach. Something more intuitive.
For example, we have a variable user_is_active
that basically contains True
if the current user is active, and False
if she hasn't activated her account yet. In your app, you'd like to do something like:
user_is_active = False # Let's simulate an inactive user
if not user_is_active:
print("You can't perform this task until your account isn't activated")
else:
print("All good. Processing your request...")
In this case, the not user_is_active
is just answering the "question" we're asking intuitively. In english, we'd express it as: If the user is not active, which in code translated to if not user_is_active
. Pretty accurate, right?
The not operator will also work with other objects, not just Booleans. For example:
remaining_credits = 0 # Let's simulate the user ran out of credits to use our app
if not remaining_credits:
print("You're out of credits")
else:
print("Delivering your order")