How to Check Multiple Conditions in if
Statements (and, or, any, all) in Python
In Python programming, if
statements often need to evaluate more than one condition to make a decision. You might need to check if all conditions are true, or if at least one condition is true. Python provides logical operators (and
, or
) and built-in functions (all()
, any()
) to handle these scenarios effectively.
This guide explains how to use these tools to check multiple conditions within your if
statements.
The Need for Multiple Conditions
Simple if
statements check a single condition. However, real-world logic often requires combining several criteria. For example:
- Is a user logged in and do they have admin privileges?
- Is the input value greater than 0 and less than 100?
- Did the operation succeed or is a retry allowed?
Python's boolean logic tools allow you to express these complex checks clearly.
Checking if ALL Conditions are True
Use these methods when the if
block should only execute if every single specified condition evaluates to True
.
Using the and
Operator
The and
operator connects two or more boolean expressions. The result is True
only if all connected expressions are True
.
age = 25
has_permission = True
is_active = True
# Check if age is over 18 AND has_permission is True AND is_active is True
if age >= 18 and has_permission and is_active:
# This block runs because all conditions are True
print("Access Granted: All conditions met.")
else:
print("Access Denied: Not all conditions met.")
# Example where one condition fails
is_active = False
if age >= 18 and has_permission and is_active:
print("Access Granted (Scenario 2).")
else:
# This block runs because is_active is False
print("Access Denied (Scenario 2): Not all conditions met.")
Python evaluates and
conditions from left to right. If it encounters a False
condition, it immediately stops evaluating the rest and the overall result is False
. This can be useful for performance and avoiding errors (e.g., checking if an object is not None
before accessing its attributes).
Using the all()
Function
The built-in all()
function takes an iterable (like a list or tuple) containing boolean values or expressions. It returns True
if all elements in the iterable are truthy, and False
otherwise. It also returns True
for an empty iterable.
value = 75
lower_bound = 0
upper_bound = 100
conditions = [
value > lower_bound, # True
value < upper_bound, # True
isinstance(value, int) # True
]
# Pass the list of conditions to all()
if all(conditions):
# This block runs because all items in 'conditions' are True
print(f"Value {value} is valid (using all()).")
else:
print(f"Value {value} is invalid (using all()).")
# Example where one condition fails
conditions_fail = [
value > lower_bound, # True
value < 50, # False
isinstance(value, int) # True (but all() stops after False)
]
if all(conditions_fail):
print(f"Value {value} is valid (Scenario 2).")
else:
# This block runs because 'value < 50' is False
print(f"Value {value} is invalid (Scenario 2 - using all()).")
- Readability:
all()
can be more readable than long chains ofand
operators, especially if the conditions are generated dynamically. - Short-circuiting:
all()
also short-circuits; it stops iterating through the iterable as soon as it finds aFalse
(or falsy) value.
Checking if ANY Condition is True
Use these methods when the if
block should execute if at least one of the specified conditions evaluates to True
.
Using the or
Operator
The or
operator connects two or more boolean expressions. The result is True
if at least one of the connected expressions is True
. It's only False
if all expressions are False
.
role = "guest"
is_owner = False
has_special_pass = True
# Check if role is 'admin' OR is_owner is True OR has_special_pass is True
if role == "admin" or is_owner or has_special_pass:
# This block runs because has_special_pass is True
print("Special Access Granted: At least one condition met.")
else:
print("Standard Access: None of the special conditions met.")
# Example where all conditions fail
has_special_pass = False
if role == "admin" or is_owner or has_special_pass:
print("Special Access Granted (Scenario 2).")
else:
# This block runs because all conditions are False
print("Standard Access (Scenario 2): None of the special conditions met.")
- Short-circuiting: Python evaluates
or
conditions from left to right. If it encounters aTrue
condition, it immediately stops evaluating the rest and the overall result isTrue
.
Using the any()
Function
The built-in any()
function takes an iterable (like a list or tuple). It returns True
if at least one element in the iterable is truthy. It returns False
if the iterable is empty or if all elements are falsy.
status_code = 404
error_flags = ["timeout", "server_error", "not_found"]
current_error = "not_found"
conditions = [
status_code >= 500, # False
current_error == "timeout", # False
current_error in error_flags # True
]
# Pass the list of conditions to any()
if any(conditions):
# This block runs because 'current_error in error_flags' is True
print("An error condition was detected (using any()).")
else:
print("No error conditions detected (using any()).")
# Example where all conditions fail
conditions_none_met = [
status_code >= 500, # False
current_error == "connection_refused" # False
]
if any(conditions_none_met):
print("An error condition was detected (Scenario 2).")
else:
# This block runs because both conditions are False
print("No error conditions detected (Scenario 2 - using any()).")
- Readability: Similar to
all()
,any()
can improve readability over long chains ofor
operators. - Short-circuiting:
any()
short-circuits, stopping iteration as soon as it finds aTrue
(or truthy) value.
Combining and
and or
(Using Parentheses)
You can mix and
and or
in a single if
statement, but you need to be careful about operator precedence. The and
operator has higher precedence than or
, meaning and
operations are typically evaluated before or
operations.
To avoid ambiguity and ensure the logic executes as intended, always use parentheses ()
to explicitly group your conditions.
score = 85
attendance = 95
has_extra_credit = False
# Incorrect without parentheses (might not be what you mean):
# if score >= 80 and attendance >= 90 or has_extra_credit: ...
# This is evaluated as: (score >= 80 and attendance >= 90) or has_extra_credit
# Correct and clear using parentheses:
# Check if (score is high AND attendance is good) OR if they have extra credit
if (score >= 80 and attendance >= 90) or has_extra_credit:
# This runs because (True and True) or False -> True or False -> True
print("Condition Met: Either high score/attendance OR extra credit.")
else:
print("Condition Not Met.")
# Different logic: Check if score is high AND (attendance is good OR they have extra credit)
if score >= 80 and (attendance >= 90 or has_extra_credit):
# This runs because True and (True or False) -> True and True -> True
print("Condition Met: High score AND (good attendance OR extra credit).")
else:
print("Condition Not Met.")
Parentheses make the evaluation order explicit and your code much easier to read and debug.
Choosing the Right Approach
and
/or
Operators: Best for a small number of fixed conditions where the logic is clear and easily expressed by chaining.all()
/any()
Functions: Often better when:- You have many conditions.
- The conditions are generated dynamically (e.g., checking properties of all items in a list).
- You find
all([...])
orany([...])
more readable than longand
/or
chains.
Conclusion
Python provides flexible ways to evaluate multiple conditions in if
statements:
- Use the
and
operator or theall()
function when all conditions must be true. - Use the
or
operator or theany()
function when at least one condition must be true. - Always use parentheses
()
to group conditions clearly when mixingand
andor
operators to control the order of evaluation and enhance readability.
Understanding these tools allows you to write precise and expressive conditional logic in your Python programs.