Sub topic 9
Logical operators: and, or, not
This chapter assumes you can run Python code and know the built-in types bool, int, str and list. It also assumes you know how comparison operators like == and < work, and that every value in Python is either truthy or falsy (empty containers, 0, None and False are falsy). Here you will learn what and, or and not return, how they group, and the mistakes that follow from misreading them.
The three operators
Python has three logical operators, written as English words:
| Operator | Meaning | Result type |
|---|---|---|
| `not x` | the opposite of the truthiness of `x` | always `bool` |
| `x and y` | `x` if `x` is falsy, otherwise `y` | `x` or `y` |
| `x or y` | `x` if `x` is truthy, otherwise `y` | `x` or `y` |
With real booleans, they behave like the usual truth tables:
print(True and False) # False
print(True or False) # True
print(not True) # False
print(not False) # Trueand and or are binary, so they take two operands. not is unary, so it takes one. Python has no &&, || or ! for logic. Those symbols are not valid Python operators.
They return an operand, not always a bool
Many languages force the result of a logical operator to be true or false. Python does not. and and or return one of the two operands themselves, whatever its type:
print(0 or "x") # x
print("a" and "b") # b
print([] and 5) # []
print("" or [] or 0) # 0The rule is the one in the table. or returns the first truthy operand, or the last operand if none is truthy. and returns the first falsy operand, or the last operand if all are truthy. In an if statement you rarely notice, because the result is only tested for truthiness. It matters when you store or print the result.
not is different. It always produces a real bool:
print(not "hello") # False
print(not []) # True
print(type(not 5)) # <class 'bool'>The diagram shows how each operator decides what to return.
The right operand is only evaluated when the left one does not decide the answer. The next chapter covers that short-circuit behavior in detail. The consequence for this chapter is that the right side may never run.
Precedence among the three
When one expression mixes the operators, they group in this order, from tightest to loosest:
- Comparisons such as
==,<andin notandor
So and binds tighter than or, in the same way that * binds tighter than +:
print(True or False and False) # True
print((True or False) and False) # False
print(not True == False) # TrueThe first line is read as True or (False and False). The third is read as not (True == False), because == groups before not. This means you do not need parentheses around comparisons inside a condition such as age >= 18 and not banned.
When an expression mixes and with or, add parentheses even where they are not required. A reader should not have to remember the precedence table to follow your condition.
Common errors
Writing `x == 1 or 2`
Beginners often translate "x is 1 or 2" word for word. Python parses x == 1 or 2 as (x == 1) or 2. The right operand is the bare number 2, which is always truthy:
x = 3
print(x == 1 or 2) # 2
print(x in (1, 2)) # False
print(x == 1 or x == 2) # FalseThe first line does not even print a boolean. In an if, the condition would be true for every value of x. Use a membership test, or repeat the full comparison on each side.
Using `or` for defaults when falsy values are valid
value or default is a common idiom, but it replaces every falsy value, not only the missing one:
count = 0
print(count or 10) # 10, even though 0 was a real answer
def pick(value, default=10):
return default if value is None else value
print(pick(0)) # 0
print(pick(None)) # 10Use or for defaults only when 0, "" and empty containers are not meaningful inputs. Otherwise test with is None.
Mixing up `and` with `&`
& and | are bitwise operators. They work on the binary digits of integers. They also bind more tightly than comparisons, so they group differently from and and or:
print(1 and 2) # 2
print(1 & 2) # 01 and 2 returns the last truthy operand. 1 & 2 compares the bits 01 and 10, which share none, so the result is 0. Use the word operators for conditions.
Chaining several operators
Each operator can be chained. The result follows the same rules, left to right:
print(1 and 2 and 3) # 3
print(1 and 0 and 3) # 0
print(0 or "" or None) # None
print(0 or "" or "ok") # okThe third line shows that when every operand is falsy, or returns the last one, not False. If you need a strict boolean from a chain, wrap it in bool(...), or compare it explicitly.
Choosing between the forms
| Goal | Prefer |
|---|---|
| Combine conditions in an `if` | `and`, `or`, `not` with parentheses where mixed |
| Pick the first usable value | `a or b`, when falsy values are not valid data |
| Pick a value only when one is missing | `a if a is not None else b` |
| Force a real boolean | `bool(expr)` or `not not expr` (less readable) |
Exercise
What do these three lines print? (1) print(0 or [] or "x") (2) print(1 and 2 and 0) (3) print(not 0 or 0)
Show answer
(1) prints x, because 0 and [] are falsy and "x" is the last operand. (2) prints 0, because and returns the first falsy operand. (3) prints True, because not 0 is True, and True or 0 returns True.
Exercise
A function contains the check if mode == "fast" or "turbo":. Why does the branch always run, and how would you fix it?
Show answer
It parses as (mode == "fast") or "turbo", and the non-empty string "turbo" is always truthy. Write if mode in ("fast", "turbo"): or if mode == "fast" or mode == "turbo":.