Logical Operators in Python
Python has three logical operators, and, or and not, written as words rather than the &&, || and ! of other languages. They combine or reverse conditions, most often in an if. and and or stop evaluating as soon as the answer is known and return one of their operands, the values on either side, while not always returns True or False.
Key facts
andis true only when both sides are true.oris true when at least one side is true.notflips a value.&&and||are syntax errors in Python. The words are the operators.andandorshort-circuit, so the right side never runs when the left side already decides the result.- Precedence is
not, thenand, thenor. Parentheses make the intent visible.
What are the three logical operators in Python?
and, or and not. The first two combine two conditions and the third reverses one. The table shows every result.
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 |
print(True and False)
print(True or False)
print(not True)False True False
How do I use and, or and not in an if statement?
Put the whole combined condition after if. Each side is a comparison or a boolean, and the operator joins them into one answer.
age = 25
has_ticket = True
if age >= 18 and has_ticket:
print("Welcome in")
day = "sat"
if day == "sat" or day == "sun":
print("Weekend")
if not has_ticket:
print("No entry")
else:
print("Ticket found")Welcome in Weekend Ticket found
Does Python use && or and?
Python uses the words. && and || come from C and JavaScript, and Python rejects them at the second character. A single & or | exists, but those are bitwise operators, not the logical ones.
a = True
b = False
print(a && b) File "main.py", line 3
print(a && b)
^
SyntaxError: invalid syntaxWhat is short-circuit evaluation?
Python stops evaluating a condition as soon as the result is known. For and, a false left side settles it, so the right side never runs. For or, a true left side settles it. In this example the right side would divide by zero, and Python never reaches it.
x = 0
print(x != 0 and 10 / x > 1)
print(x == 0 or 10 / x > 1)False True
To guard a risky operation, put the check on the left of and and the operation on the right.
What do and and or actually return?
One of their operands, the values on either side of the operator, not necessarily a boolean. or returns the first truthy value it meets, or the last value if none is truthy. and returns the first falsy value, or the last value if all are truthy. Inside an if you never notice. Outside one, or gives you a one-line default.
print(0 or "default")
print("first" or "second")
print("first" and "second")
print(0 and "never")
name = ""
print(name or "Anonymous")default first second 0 Anonymous
name or "Anonymous" keeps the name when there is one and falls back to "Anonymous" when it is empty. The fallback applies to any falsy value, so count or 10 also replaces a real 0.
What is the precedence of not, and and or?
Precedence is the order in which Python applies operators. Of the three, not binds tightest, then and, then or.
So not a or b means (not a) or b, and a or b and c means a or (b and c). Comparisons such as == bind tighter still, so not a == b means not (a == b). When a condition mixes them, add the parentheses even though Python doesn't need them.
print(not True or True)
print(not (True or True))
print(True or False and False)
print((True or False) and False)True False True False
How do I test membership or use exclusive or?
in and not in test whether a value is inside a string or collection. They replace long or chains. Python has no xor keyword. For two booleans, a != b is True when exactly one of them is true, and the ^ operator gives the same result.
a = True
b = True
print(a != b)
print(a ^ b)
print("a" in "cat", "z" not in "cat")False False True True
Common mistakes with logical operators in Python
Three of these mistakes with logical operators raise no error. The first reads like correct code, so it is the hardest to spot.
x == 1 or 2always counts as true. Python groups it as(x == 1) or 2, and2is truthy. Writex == 1 or x == 2, orx in (1, 2).- SyntaxError: invalid syntax on
&&. Useand. Likewise, writeorinstead of||andnotinstead of!. - Mixing
andandorwithout parentheses. It runs, and it may not mean what you read. Group the parts. - Expecting
orto giveTrueorFalse. It gives one of the operands. Wrap it inbool()when you need a boolean value to store.
x = 5
print(x == 1 or 2)
print(x == 1 or x == 2)
print(x in (1, 2))2 False False
Exercise
Complete the two print lines. The first prints whether the person may enter, which needs both an age of at least 18 and a ticket, so True. The second prints the opposite of has_ticket, so False.
age = 25
has_ticket = True
print()
print()
True False
Show the solution
age = 25
has_ticket = True
print(age >= 18 and has_ticket)
print(not has_ticket)
Quiz
This quiz has 5 questions. Pick an answer to see why it is right or wrong.
-
1What does this program print?
print(False or 7)or returns the first truthy operand, which is 7, not a boolean.
-
2What does this program print?
x = 3 print(x == 1 or 2)x == 1 is False, so or returns the other operand, the number 2, which counts as true in an if.
-
3Which is the Python equivalent of && in other languages?
The keyword and, in lowercase. & is the bitwise operator, and both && and AND in capitals are syntax errors.
-
4What does this program print?
print(not False and False)not binds tighter than and, so it reads as (not False) and False, which becomes True and False, and that is False.
-
5When this code runs, what happens to the division 10 / x?
x = 0 result = x != 0 and 10 / x > 1The left side is False, so and already knows the answer and skips the right side. That is short-circuit evaluation.