and, or, not (logical operators)
and, or and not combine and flip conditions: and needs both sides true, or needs one, and not turns True into False.
a and b
a or b
not aand is true only when both sides are true. or is true when at least one side is true. not turns true into false and false into true. Together they let one if test several things.
Python stops as soon as it knows the answer, which is called short-circuiting. With and, a false left side means the right side is never evaluated; with or, a true left side is enough. This lets you write safe checks like if items and items[0] > 0:.
Surprise: and and or do not always give True or False. They return one of the two values themselves. name or "Guest" gives name if it is not empty, otherwise "Guest", a popular way to set a default.
Return value
and / or: one of the two operands. not: always True or False.
Examples
1The three operators
sunny = True
weekend = False
print(sunny and weekend)
print(sunny or weekend)
print(not weekend)False True True
2In an if
age = 25
has_ticket = True
banned = False
if age >= 18 and has_ticket and not banned:
print("Welcome in")Welcome in
3Short-circuit keeps you safe
orders = []
if orders and orders[0] > 100:
print("Big first order")
else:
print("No big first order")No big first order
Because orders is empty (false), Python never looks at orders[0], which would raise IndexError.
4or for a default value
def greet(name):
name = name or "Guest"
print("Hello,", name)
greet("Rosa")
greet("")Hello, Rosa Hello, Guest
5They return a value, not just True/False
print(0 or 5)
print("" and "never seen")
print([1] and "list not empty")
print(not "")5 list not empty True
The second line prints an empty string, so you see a blank line.
Common mistakes
Mixing and and or without brackets
and is applied before or, like multiplication before addition. Add brackets to make your meaning clear.
is_admin = True
is_owner = False
is_locked = True
print(is_admin or is_owner and not is_locked)
print((is_admin or is_owner) and not is_locked)True False
Using & and | for conditions
& and | are bit operators on numbers (and set operators). For true/false logic use the words and and or, which also short-circuit.
or with a value that may be 0
count = given or 10 also replaces a real 0 with 10, because 0 is false. If 0 is valid, test for None instead: count = 10 if given is None else given.
Questions people ask
What is the order of not, and, or?
not first, then and, then or. Use brackets when in doubt.
Does Python have && and ||?
No. Python uses the words and, or and not.