Sub topic 5
Combining conditions with and, or, not
This chapter assumes you know Python's bool type, truthiness, and comparison operators from the earlier chapters. Here you will combine several conditions into one expression and avoid the usual mistakes.
The three operators
Python has three boolean operators, written as words:
andis true when both sides are true.oris true when at least one side is true.notflips a single value.
| 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 |
Each side can be any expression, usually a comparison:
age = 25
has_ticket = True
print(age >= 18 and has_ticket) # True
print(age < 18 or not has_ticket) # False
print(not age == 30) # TrueComparisons are evaluated first, so you do not need parentheses around age >= 18. The expression not age == 30 means not (age == 30). Writing age != 30 is usually clearer.
Precedence
When one expression mixes the operators, Python evaluates them in this order, from tightest to loosest:
- Comparisons such as
<,==, andin notandor
This means and groups before or:
a, b, c = True, False, False
print(a or b and c) # True, read as a or (b and c)
print((a or b) and c) # FalseThe two lines give different answers. Add parentheses whenever a reader might have to stop and work out the grouping. Parentheses cost nothing.
Operands, not just True and False
The result of and and or is not always a bool. Each returns one of its operands, and the next chapter covers this in detail. For now, remember that a and b and a or b can return any type. When you need a real bool, wrap the expression in bool().
print(3 > 2 and 5 > 4) # True
print("" or "fallback") # fallback
print(bool("" or "fallback")) # TrueCommon errors
Repeating the comparison
English lets you say "if the color is red or blue". Python does not.
color = "green"
print(color == "red" or "blue") # blue
print(color in ("red", "blue")) # FalseThe first line is read as (color == "red") or "blue". The left side is false, so the result is the string "blue", which is always truthy. An if using this condition would always run. Write the comparison on both sides, or use in with a tuple.
Misreading a negated condition
Negating a combined condition changes both the operator and each part. These rules are called De Morgan's laws:
not (a and b)equalsnot a or not bnot (a or b)equalsnot a and not b
x = 5
print(not (x > 1 and x < 3)) # True
print(x <= 1 or x >= 3) # TrueWhen a negated condition is hard to read, rewrite it in the positive form.
Using & and | by mistake
The symbols & and | are bitwise operators. They have different precedence from and and or, and they do not short-circuit. Use the word operators for conditions. Libraries such as pandas and NumPy use & and | on purpose for element-wise logic, but that is a separate case.
Putting it together
A small validation function shows how the pieces fit:
def can_rent_car(age, has_license, is_banned):
return age >= 21 and has_license and not is_banned
print(can_rent_car(30, True, False)) # True
print(can_rent_car(30, True, True)) # False
print(can_rent_car(19, True, False)) # FalseBecause every operand here is a bool or a comparison, the function returns a bool.
Exercise
What does not 1 < 2 or 3 < 4 and 5 < 4 print, and in what order does Python group it?
Show answer
It prints False. Comparisons are evaluated first: 1 < 2 is True, 3 < 4 is True, 5 < 4 is False. Then not applies to the first comparison, giving False. Then and groups before or, so the expression is (not True) or (True and False), which is False or False, which is False.
Exercise
Rewrite if not (status == "open" or status == "pending"): without the outer not, and without using not at all.
Show answer
Use De Morgan's laws: if status != "open" and status != "pending":. Both parts are negated and or becomes and.