We can combine boolean values, or expressions like value < 3 or text == “Hello” that evaluate to a boolean value, using boolean operators.
and and or are binary operators: the accept two arguments and return a boolean value.
not is a unary operator. It accepts only one argument and returns a boolean value.
- and returns True if both arguments are True, otherwise it returns False
- or returns True if either or both arguments are True, otherwise it returns False
- not simply returns the converse of the value it’s applied to. It returns True if applied to a False value, or False if applied to a True value.
Boolean Operators Example
raining = True cold = False windy = False if raining and cold: print("Bad weather. Take a coat.") else: print("Might be OK without a coat.") # This is the same as if raining and (not windy) if raining and not windy: print("Take an umbrella") # This is the same as if (raining or cold) or windy if raining or cold or windy: print("Not the nicest weather today.")
Might be OK without a coat. Take an umbrella Not the nicest weather today.
We can create arbitrarily complicated boolean expressions, but it’s best not to go too overboard with them, since long expressions can be hard to read.
You can use brackets to help make expressions clearer.
Note that binary boolean operators only operate on two things at a time. So an expression like raining or cold or windy will first convert raining or cold to a simple True or False value, then the or operator gets applied to that value, together with windy.