Combine conditions with and, or and not, and learn when Python stops early.
and operator
# and - both must be True
True and True
# ans: True
True and False
# ans: False
False and True
# ans: False
False and False
# ans: False
Two switches in a row: the lamp lights only if both are closed.
or operator
# or - at least one True
True or False
# ans: True
False or True
# ans: True
False or False
# ans: False
True or True
# ans: True
Two switches side by side: either one closed lights the lamp.
not operator
# not - inverts boolean
not True
# ans: False
not False
# ans: True
not (5 > 3)
# ans: False
# combining with and
x = 10
x > 5 and x < 15
# ans: True
# combining with or
x < 5 or x > 8
# ans: True
# and stops at first False
False and (1/0)
# ans: False (no error, doesn't evaluate 1/0)
# or stops at first True
True or (1/0)
# ans: True (no error)
Once the left side settles the answer, Python never runs the right side, so the division by zero never happens.
Work out each value, then press →.
# what is the result?
True and True
# ans: True
# short circuit evaluation?
False and (1/0)
# ans: False (no error, doesn't evaluate second part)
# short circuit with or?
True or (1/0)
# ans: True (no error)
# what about this?
not False
# ans: True
# chaining and/or?
True or False and False
# ans: True (and has higher precedence)
# boolean with comparison?
5 > 3 and 10 < 20
# ans: True
# tricky: what is this?
bool([]) and bool([1])
# ans: False
# what evaluates?
0 or 5
# ans: 5 (returns last truthy value)
and / or return one of their operands, not necessarily True or False.
# and returns?
5 and 10
# ans: 10 (returns last value if all truthy)
# mixed types?
"hello" and ""
# ans: "" (returns last value or first falsy)
# what about this?
not not True
# ans: True
# De Morgan's law?
not (True and False)
# ans: True
not True or not False
# ans: True
De Morgan: not (a and b) is the same as not a or not b.
# order of precedence?
True and False or True
# ans: True (and first, then or)
# empty values?
[] or [1, 2]
# ans: [1, 2]
andTrue only if both sides are true.
orTrue if at least one side is true.
not binds tightest, then and, then or.
Python stops as soon as the answer is known and returns the value that decided it.