Three Words Instead of Symbols
Python's logical operators are the English words and, or and not. Other languages spell them &&, || and !. In Python && and || are a SyntaxError, and ! only appears as part of != ("not equal").
With True and False the rules are the ones you expect:
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 |
and needs both sides to be true. or needs at least one. not takes a single value and inverts it.
In real code the sides are usually comparisons, and the result feeds an if or a while:
Output:
eligible
standard ticket
That much is enough for most conditions. The rest of this page covers what the operators do with values that are not True or False, and the rules that decide which side of an expression runs.
Truthy and Falsy Values
and, or and not accept any value, not only booleans. Python decides whether a value counts as true by its truthiness. These values are falsy:
FalseandNone- zero of any number type:
0,0.0 - empty containers and strings:
"",[],(),{},set(),range(0)
Everything else is truthy, including "0", "False", [0] and -1. You can see how Python classifies a value with bool():
Output:
0 False
1 True
-1 True
'' False
'0' True
[] False
[0] True
None False
0.0 False
The string "0" is truthy because it is a non-empty string. That one catches people who read numbers from input and test them before converting. The numbers and booleans page covers how bool relates to int.
and and or Return an Operand
This is where Python differs from most languages. and and or do not produce a fresh True or False. They return one of the two values you gave them:
x or yreturnsxifxis truthy, otherwise it returnsy.x and yreturnsxifxis falsy, otherwise it returnsy.
When both operands are booleans, "return an operand" and "return a boolean" are the same thing, which is why the difference goes unnoticed until you mix in other types.
not is the exception: it always returns True or False.
If you need a real boolean from an and/or expression, for example to store it or return it from a function that promises bool, wrap it in bool():
Short-Circuit Evaluation
Python evaluates and and or from left to right and stops as soon as the answer is known:
andstops at the first falsy value, because nothing after it can make the whole expression true.orstops at the first truthy value, because nothing after it can make the whole expression false.
The skipped side is not run at all. You can watch this happen with functions that print when they are called:
Output:
and:
checking A
False
or:
checking A
True
B is never checked in either case. Short-circuiting is what makes guard conditions safe. The second half of each condition below would crash on its own, but it only runs once the first half has ruled out the bad case:
Put the cheap or protective test first. Reversing the order, user.startswith("admin") and user is not None, raises AttributeError when user is None.
Patterns Built on or and and
Because or returns its first truthy operand, it gives a one-line default value:
Output:
Hello, Ada!
Hello, guest!
Hello, guest!
The catch is that or replaces every falsy value, not only None. If 0, "" or [] is a legitimate input, or will throw it away:
Use x if x is not None else default when zero or empty is a valid value. The if/else page covers that conditional expression.
and has a matching pattern: "use this value only if the first one is set". It is less common and often clearer as an if, so reach for it sparingly:
Precedence: not, then and, then or
When an expression mixes the three, Python applies not first, then and, then or. Comparisons such as ==, < and in are applied before any of them.
a or b and c and (a or b) and c give different answers from the same values, so a mixed condition should carry parentheses even when the default order happens to be right. They cost nothing and remove the question for the next reader.
and/or vs &/|
& and | look similar to and and or and sometimes give the same answer, but they are different operators.
and/ortest truthiness, short-circuit, and return one of the operands.&/|are bitwise operators. On integers they combine the bits of the two numbers. On sets they mean intersection and union. OnTrueandFalsethey return a boolean. They never short-circuit: both sides are always evaluated.
The bitwise operators also have higher precedence than comparisons, which turns a condition written with & into something else entirely:
1 & y is 1 & 5, which is 1, so the middle line becomes the chain 5 > 1 > 1, and 1 > 1 is false. In plain Python code, use and, or and not for conditions.
The one place &, | and ~ are correct for conditions is NumPy and pandas. An array holds many values, so it has no single truth value, and and raises ValueError: The truth value of an array ... is ambiguous. The libraries overload & and | to work element by element, which is why pandas filters look like df[(df.age > 18) & (df.country == "CA")], with parentheses around each comparison for the precedence reason above.
any() and all(): and and or Over a List
To combine a whole sequence of conditions, use the built-ins all() (an and across every item) and any() (an or across every item). Both short-circuit the same way:
Unlike and and or, any() and all() always return a boolean.
Common Mistakes
Comparing one variable against several values with or. This condition is always true:
Python reads the first condition as (color == "red") or "blue". The comparison is False, so or returns "blue", a non-empty string, which is truthy. Repeat the comparison on both sides, or better, test membership with in.
Writing && or ||. Both are a SyntaxError. Use and and or.
Expecting a boolean from and/or. x = a or b stores a or b itself. That is often what you want, but if a function should return True or False, convert with bool().
Relying on precedence in mixed conditions. a or b and c is legal and well defined, but add parentheses so nobody has to remember the rule.
Frequently Asked Questions
What does the and operator do in Python?
a and b is true only when both sides are true. Python evaluates a first; if a is falsy it returns a without looking at b, otherwise it returns b. With plain booleans that gives the usual result: True and False is False.
Why does 0 or 5 return 5 instead of True?
0 or 5 return 5 instead of True?or and and return one of their operands, not a new boolean. x or y returns x if x is truthy, otherwise y. 0 is falsy, so 0 or 5 returns 5. Wrap the expression in bool() if you need a real True or False.
What is the difference between and and & in Python?
and and & in Python?and is a logical operator: it tests truthiness and short-circuits. & is a bitwise operator: on integers it combines bits (6 & 3 is 2), on sets it takes the intersection, and it always evaluates both sides. Use and in if conditions. The exception is NumPy and pandas, where & is the element-wise and.
Which runs first in Python, and or or?
not binds tightest, then and, then or. So a or b and c means a or (b and c), and not a or b means (not a) or b. Comparisons such as == and < bind tighter than all three.
Can I use && and || in Python?
No. && and || are a SyntaxError in Python. The logical operators are the words and, or and not. A single & or | is valid but means something else (bitwise and/or).