When handling conditional branches like if statements in Python, you often want to combine multiple conditions. For example, “User is authenticated AND is an administrator” or “Process failed OR timed out.”
To achieve this, Python provides Boolean Operators (Logical Operators): and, or, and not.
This article explains how to use these three operators and the important concept of “Short-Circuit Evaluation.”
not Operator (Logical Negation)
The not operator reverses a boolean value.
not TruebecomesFalse.not FalsebecomesTrue.
It is used to specify a “is NOT” condition.
is_active_user = False
# Evaluates to True because is_active_user is False
if not is_active_user:
print("User is not active.")
# ---
is_connected = True
# Since is_connected is True, adding 'not' makes it False
if not is_connected:
print("Not connected.") # This line is not executed
Output:
User is not active.
and Operator (Logical AND)
The and operator evaluates to True only if both conditions are True. If even one is False, the result is False.
This corresponds to the condition “A AND B”.
| A | B | A and B |
| True | True | True |
| True | False | False |
| False | True | False |
| False | False | False |
# Permission check example
is_authenticated = True # Logged in
is_admin = False # Not an admin
# Must be authenticated AND be an admin
if is_authenticated and is_admin:
print("Access allowed to Admin Menu.")
else:
print("Access denied. ('and' condition is False)")
Output:
Access denied. ('and' condition is False)
or Operator (Logical OR)
The or operator evaluates to True if at least one of the conditions is True. It evaluates to False only if both are False.
This corresponds to the condition “A OR B”.
| A | B | A or B |
| True | True | True |
| True | False | True |
| False | True | True |
| False | False | False |
# Error check example
has_network_error = False
has_timeout = True
# If network error OR timeout occurred
if has_network_error or has_timeout:
print("Process failed. ('or' condition is True)")
else:
print("Process completed successfully.")
Output:
Process failed. ('or' condition is True)
Important Concept: Short-Circuit Evaluation
The and and or operators perform a very important behavior called “Short-Circuit Evaluation.”
This means that Python stops evaluating the expression as soon as the result is determined.
1. Short-Circuiting with and
In A and B: If A is False, the entire result is guaranteed to be False (regardless of B).
Therefore, Python does not evaluate B if A is False.
2. Short-Circuiting with or
In A or B: If A is True, the entire result is guaranteed to be True (regardless of B).
Therefore, Python does not evaluate B if A is True.
Benefits of Short-Circuit Evaluation
This mechanism helps improve efficiency and avoid errors.
Example: Avoiding Errors
It is often used to check if an object is not None before calling a method on it.
user_object = None # Assume the user object does not exist yet
# If there were no short-circuit evaluation, Python would try to run
# 'user_object.is_active()' and crash with:
# 'NoneType' object has no attribute 'is_active'
#
# Thanks to 'and' short-circuiting:
# 1. 'user_object is not None' evaluates to False.
# 2. The right side 'user_object.is_active()' is SKIPPED.
# 3. The if statement becomes False safely, avoiding the crash.
if user_object is not None and user_object.is_active():
print(f"{user_object.name} is active.")
else:
print("User does not exist or is not active.")
Output:
User does not exist or is not active.
Summary
not: Reverses the boolean value (“Not A”).and: ReturnsTrueonly if both are True (“A and B”).or: ReturnsTrueif at least one is True (“A or B”).- Short-Circuit Evaluation:
and: If the left side isFalse, the right side is ignored.or: If the left side isTrue, the right side is ignored.
