Sub topic 5
Combining conditions with and, or, not
This chapter assumes you know how bool values, truthiness, and comparison operators work, as covered in the earlier chapters. You should also be comfortable writing if statements and small functions. Here you will learn how and, or, and not combine conditions, how they group when you mix them, and which mistakes to avoid.
The three operators
Python has three logical operators, and they are spelled as English words.
x and yis true when both sides are true.x or yis true when at least one side is true.not xflips the truth value ofx.
The table shows the result for every combination of two boolean inputs.
| a | b | a and b | a or b | not a |
|---|---|---|---|---|
| True | True | True | True | False |
| True | False | False | True | False |
| False | True | False | True | True |
| False | False | False | False | True |
Here are the same rules in code. Operands do not have to be booleans. Any object can be tested for truthiness.
a, b = True, False
print(a and b, a or b, not a) # False True False
print(not 0, not "text", not []) # True False Truenot always returns a real bool, whatever you give it. That makes it the one logical operator with a predictable result type. and and or behave differently, as the next section explains.
What and and or actually return
and and or do not always return True or False. They return one of their two operands. The next chapter covers this fully along with short-circuiting. For now, you need the rule to read mixed conditions correctly.
| Expression | Returns |
|---|---|
| `x and y` | `x` if `x` is falsy, otherwise `y` |
| `x or y` | `x` if `x` is truthy, otherwise `y` |
| `not x` | `True` if `x` is falsy, otherwise `False` |
When both operands are booleans, the result is a boolean too, so the truth table above holds. With other types, the result is whichever operand decided the outcome.
print(3 and 5) # 5
print(0 and 5) # 0
print("" or "none") # none
print(not "none") # FalseIn an if statement, only the truthiness of the final result matters, so you rarely notice the difference. It matters when you store the result in a variable or print it.
Precedence: not, then and, then or
When you write several operators in one expression, Python groups them by precedence. From tightest to loosest, the relevant order is:
- Comparisons and membership tests:
==,!=,<,>,in,not in,is,is not notandor
So and binds tighter than or, in the same way that * binds tighter than +. And not binds looser than comparisons, so not a == b means not (a == b).
print(True or False and False) # True
print((True or False) and False) # False
print(not 1 == 2) # True
print(not True == False) # TrueThe first line groups as True or (False and False), which is True or False, which is True. The second line uses parentheses to force a different grouping, and the answer changes. The last two lines show that not applies to the whole comparison on its right.
Read the diagram from the top. The comparison and the not are evaluated first. Their results meet at and. That result then meets is_admin at or. The condition therefore means "an adult who is not banned, or an admin".
A realistic condition
Here is a function that combines all three operators with comparisons.
def can_enter(age, banned, is_admin):
return (age >= 18 and not banned) or is_admin
print(can_enter(25, False, False)) # True
print(can_enter(25, True, False)) # False
print(can_enter(12, True, True)) # TrueThe function returns a bool here because every operand is a bool. If age were None, the expression age >= 18 would raise TypeError, which a later chapter covers. Logical operators do not protect you from invalid comparisons.
Common mistake: comparing against "a or b"
The most frequent error with or is writing it the way you would say it in English.
color = "green"
print(color == "red" or "blue") # blue
print(bool(color == "red" or "blue")) # True
print(color in ("red", "blue")) # FalsePython reads color == "red" or "blue" as (color == "red") or "blue". The left side is False, so or returns the right side, the non-empty string "blue". That string is always truthy, so an if on this expression is always taken, whatever color holds.
There are two correct ways to write the check:
- Repeat the comparison:
color == "red" or color == "blue". - Use a membership test:
color in ("red", "blue").
The membership test is shorter and scales to many values. The same mistake happens with and, for example x == 1 and 2.
not versus the negated operators
You can negate a comparison two ways: put not in front, or use the opposite operator. Both work, and the second reads better.
x = 4
print(not x == 5) # True
print(x != 5) # True
items = [1, 2, 3]
print(not 9 in items) # True
print(9 not in items) # True
value = None
print(not value is None) # False
print(value is not None) # Falsenot in and is not are single operators, not a not applied to something. Style guides prefer them because they read like English. Note that not x == y and x != y are only identical for ordinary types. For objects with a custom __eq__, != may be defined separately, and values such as NaN make "not equal" and "not (equal)" worth thinking about on their own. A later chapter on pitfalls returns to NaN.
Rewriting conditions with De Morgan's laws
Two identities help you simplify negated conditions:
not (a and b)equals(not a) or (not b).not (a or b)equals(not a) and (not b).
They are useful when a condition has become hard to read because of stacked not operators. The next example checks that two forms of a rule agree for every input.
def blocked(age, member):
return not (age >= 18 and member)
def blocked_expanded(age, member):
return age < 18 or not member
for age in (10, 30):
for member in (True, False):
assert blocked(age, member) == blocked_expanded(age, member)
print("equivalent") # equivalentNotice that negating age >= 18 gives age < 18. Pushing the not inward and replacing it with the opposite comparison is the usual way to clean up a condition. Be careful with this on values like NaN, where not (x >= 18) and x < 18 are not the same.
Do not confuse and, or, not with &, |, ~
Python also has the bitwise operators &, |, and ~. They work on integer bits, not on truth values. Because bool is a subclass of int, they accept booleans, and & and | even return a bool for two booleans. That makes the mix-up easy to miss.
print(True & False, True | False) # False True
print(~True, ~False) # -2 -1
print(not True, not False) # False True
x = 20
print(x > 1 and x < 10) # False
print(x > 1 & x < 10) # True~True is -2, not False, because ~ computes -(n + 1) on the integer value. The last two lines show the usual trap. & binds tighter than comparisons, so the second expression becomes x > (1 & x) < 10. With x = 20, 1 & 20 is 0, and the chained comparison 20 > 0 < 10 is true, which is the wrong answer.
Use and, or, and not for conditions. Use & and | only for bit manipulation and for libraries such as pandas and NumPy, where they are required and the comparisons must be wrapped in parentheses.
Summary of rules
not xalways returns abool.andandorreturn one of their operands.- Precedence from tightest to loosest is comparisons,
not,and,or. - Use parentheses to make mixed
and/orconditions explicit. - Never write
x == a or bwhen you meanx == a or x == b. Usex in (a, b). - Prefer
!=,not in, andis notover a leadingnot. - Do not substitute
&,|, or~for the logical operators.
Exercise
Without running it, what does each line print? Then explain the grouping of the third line. print(not 0 and "yes") print(0 or [] or "fallback") print(True or False and not True)
Show answer
The first line prints yes. not 0 is True, and True and "yes" returns the second operand, "yes". The second line prints fallback: 0 and [] are falsy, so or moves on and returns the last operand. The third line prints True. It groups as True or (False and (not True)). Since not binds tightest, then and, then or, the and part is False and False, which is False, and True or False is True.
Exercise
This function is meant to return True for the weekend days "sat" and "sun", but it returns True for every input. Explain why, then fix it in two ways. def is_weekend(day): return day == "sat" or "sun"
Show answer
Python reads it as (day == "sat") or "sun". When day is not "sat", the left side is False, so or returns "sun", which is a non-empty string and therefore truthy. Fix 1: return day == "sat" or day == "sun". Fix 2: return day in ("sat", "sun"). Both return a real bool for any string input.