Python Logical Operators: and, or, and not
Learn how Python's and, or, and not operators combine and negate Boolean expressions, with truth tables, short-circuiting, truthiness, and practical examples.
Python logical operators combine or reverse conditions. The three logical operators are and, or, and not. They are especially useful in if and elif statements when a decision depends on more than one rule.
This lesson assumes that you understand variables, basic values, and comparison operators.
Boolean values and Boolean expressions
A Boolean is a value representing truth. Python has two Boolean values: True and False.
A Boolean expression is an expression that evaluates to True or False. Comparisons create Boolean values:
5 < 7 # True
3 == 3 # True
10 != 10 # False
8 > 12 # False
Comparison operators such as <, >, ==, and != answer one comparison. Logical operators combine or invert the results of those comparisons.
Logical operators at a glance
An operand is a value or expression that an operator acts upon. and and or normally have two operands, so they are binary operators. not has one operand, so it is a unary operator.
The and operator
The and operator is true only when both operands are true. In a two-condition expression, any false operand makes the entire result false.
5 < 7 and 5 > 3 # True
3 > 3 and 55 > 30 # False
55 == 55 and 3 <= 3 # True
In the first example, both comparisons are true. In the second, 3 > 3 is false, so the complete and expression is false even though the second comparison is true.
Truth table for and
Use and when every condition must be satisfied, such as checking that a number is within an inclusive range:
age = thirty
The preceding line intentionally contains invalid syntax as an example of what not to write. A working example is:
age = thirty # Do not use this
age = 30
if age >= 18 and age <= 65:
print("Age is within the range")
The or operator
The or operator is true when at least one operand is true. It is false only when both operands are false.
3 == 3 or 5 < 3 # True
12 <= 1 or 5 < 1 # False
The first expression is true because its left comparison is true. The right side does not need to be true when one acceptable alternative has already been found.
Truth table for or
Use or when any one of several conditions is sufficient:
role = "editor"
if role == "admin" or role == "editor":
print("Access granted")
The not operator
The not operator reverses a Boolean value. It is a unary operator because it acts on one operand.
not True # False
not False # True
not (5 > 3) # False
not (5 < 3) # True
Truth table for not
Parentheses are useful when negating a compound expression. In this example, the grouped expression is evaluated first:
not (5 < 3 and 5 < 33) # True
The evaluation works as follows:
5 < 3isFalse.5 < 33isTrue.False and TrueisFalse.not FalseisTrue.
Evaluating grouped logical expressions
When reading a logical expression, first evaluate the comparison expressions. Then apply the logical operators according to their grouping.
result = not (temperature < 0 and temperature > -20)
For a particular value, replace the variable with its value and work from the inside outward. Parentheses make the intended grouping explicit and reduce mistakes, especially when and, or, and not appear together.
Operator precedence and parentheses
Operator precedence is the set of rules that determines which operations Python evaluates first. For common Boolean expressions, the order is:
- Comparisons such as
<,==, and!=. not.and.or.
not active and admin or owner
Python reads that as:
((not active) and admin) or owner
Do not rely on readers remembering precedence when the condition is complex. Use parentheses to show the intended logic:
if (is_active and is_admin) or is_owner:
print("Allowed")
Parentheses are also recommended when applying not to more than a single comparison:
if not (is_expired or is_revoked):
print("Credential is usable")
Short-circuit evaluation
Short-circuit evaluation means Python stops evaluating a logical expression when later operands cannot change the result.
- For
and, a false left operand is enough to determine that the result is false. - For
or, a true left operand is enough to determine that the result is true.
This behavior can safely guard an operation that requires a value to exist or contain data:
text = "#Python"
if text and text[0] == "#":
print("The text starts with a hash")
If text is an empty string, the left side is false and Python does not evaluate text[0]. This prevents an indexing error. Put the safe guard first:
# Good: check that text is nonempty before indexing
text and text[0] == "#"
# Risky: indexing happens first
text[0] == "#" and text
Truthiness in Python
Python can use values other than literal True and False in conditions. Python tests whether each value is truthy or falsy.
A falsy value is treated as false. Common falsy values include:
FalseNone- Numeric zero, such as
0or0.0 - An empty string, such as
"" - An empty collection, such as
[],(), or{}
Nonzero numbers, nonempty strings, and nonempty collections are generally truthy.
bool([]), bool([1]), bool(0), bool("hello")
# (False, True, False, True)
When the operands are Boolean expressions, logical operators produce the expected Boolean result. With arbitrary objects, and and or can return one of their operand values rather than a literal Boolean:
"hello" and 42 # 42
"" or "fallback" # "fallback"
In everyday condition writing, keep the main focus on what is truthy or falsy and use bool() when you need an explicit Boolean value.
Using logical operators in conditional statements
Logical operators commonly appear in if and elif statements. A condition controls whether an indented block runs.
Requiring a numeric range
score = 82
if score >= 0 and score <= 100:
print("Score is valid")
else:
print("Score is outside the valid range")
Allowing one of several options
day = "Sun"
if day == "Sat" or day == "Sun":
print("It is the weekend")
elif day == "Fri":
print("The weekend is near")
Excluding a condition
is_closed = False
if not is_closed:
print("The store is open")
Use clear variable names, format long conditions across lines when needed, and add parentheses when the logic is not immediately obvious.
Common mistakes
Confusing logical and bitwise operators
and, or, and not are logical operators. &, |, and ~ are bitwise operators that work at the level of binary bits. For ordinary Boolean conditions, write:
if is_valid and is_active:
print("Continue")
Do not replace it with is_valid & is_active unless you specifically need bitwise behavior.
Using assignment instead of comparison
= assigns a value. == compares two values. Use == when testing a condition:
role = "admin"
if role == "admin":
print("Administrator")
Using or for a range
This condition accepts almost every number because nearly every number is either at least 50 or at most 100:
if score >= 50 or score <= 100:
print("This is usually too permissive")
Use and when both boundaries must be satisfied:
if score >= 50 and score <= 100:
print("Score is between 50 and 100")
Omitting parentheses in mixed conditions
not active and admin is interpreted as (not active) and admin, because not has higher precedence than and. If your intended meaning is different, write the grouping explicitly.
Assuming a false result means every comparison was false
An and expression is false if at least one comparison is false; the other comparison might still be true. Evaluate each comparison separately while debugging:
age = 70
print(age >= 18) # True
print(age <= 65) # False
print(age >= 18 and age <= 65) # False
Putting a risky operation before its guard
This can fail when text is empty:
text[0] == "#" and text
Check the value first so short-circuiting can protect the operation:
text and text[0] == "#"
Trying logical expressions interactively
You can evaluate expressions in Python's interactive shell. Start the shell with python, then enter expressions at the prompt:
python
5 < 7 and 5 > 3
# True
3 == 3 or 5 < 3
# True
not (5 < 3 and 5 < 33)
# True
For more ways to run Python, see Python's interactive prompt and how to run Python code.
Summary
TrueandFalseare Python's Boolean values.- Comparison operators create Boolean expressions; logical operators combine or negate them.
andis true only when both operands are true.oris true when at least one operand is true.notreverses the truth value of its operand.- Python commonly evaluates comparisons first, then
not,and, andor. - Use parentheses to make mixed conditions clear.
- Short-circuit evaluation can skip unnecessary or unsafe operations.
- Values such as zero and empty collections are falsy; nonzero and nonempty values are generally truthy.
For related lessons, review comparison operators, if and elif statements, and assignment operators.