The Python or operator is a logical operator that returns True if at least one of the operands evaluates to True. It's a binary operator typed as plain English word "or" and is used to create compound Boolean expressions in conditional statements, loops, and function logic.
Basic or Operator Syntax
The or operator takes two operands and evaluates whether at least one is true.
condition1 or condition2 The or operator returns True when at least one operand is True. It only returns False when both operands are False.
Example 1: Basic Boolean Expression
bool1 = 2 > 3 # False
bool2 = 2 < 3 # True
result = bool1 or bool2
print(result) True
Example 2: Both False
bool1 = 2 > 3 # False
bool2 = 5 > 10 # False
result = bool1 or bool2
print(result) False
When both conditions are False, the or operator returns False.
Truth Table for or Operator
Understanding how the or operator works with different boolean combinations is essential.
| Condition 1 | Condition 2 | Result |
|---|---|---|
| True | True | True |
| True | False | True |
| False | True | True |
| False | False | False |
The or operator returns True when at least one operand is True.
Example: All Truth Table Cases
# Case 1: True or True = True
if True or True:
print("Case 1: True") # This executes
# Case 2: True or False = True
if True or False:
print("Case 2: True") # This executes
# Case 3: False or True = True
if False or True:
print("Case 3: True") # This executes
# Case 4: False or False = False
if False or False:
print("Case 4: True")
else:
print("Case 4: False") # This executes Case 1: True Case 2: True Case 3: True Case 4: False
How OR Works with Non-Boolean Values
Python's or operator returns the first object that evaluates to true, or the last object if all are false.
Example: OR with Different Data Types
# Returns first truthy value or last value
print(2 or 3) # Output: 2
print(5 or 0.0) # Output: 5
print([] or 3) # Output: 3
print(0 or {}) # Output: {}
print('' or 'Hello') # Output: Hello 2
5
3
{}
Hello The or operator returns the first truthy value, or the last value if all are falsy.
Falsy values (evaluated as False):
- False
- None
- 0, 0.0
- Empty string ''
- Empty list []
- Empty dict {}
- Empty tuple ()
Truthy values (evaluated as True):
- Non-zero numbers (positive or negative)
- Non-empty strings
- Non-empty collections
- True
Short-Circuit Evaluation
The or operator uses short-circuit evaluation, stopping as soon as it finds a truthy value and not evaluating remaining operands.
Example: Demonstrating Short-Circuit
def true_func():
print("First function called")
return True
def false_func():
print("Second function called")
return False
# Second function never executes
result = true_func() or false_func()
print(result) First function called True
Notice that "Second function called" never prints because true_func() returned True, so Python skipped evaluating false_func(). This optimization improves performance and prevents unnecessary computations.
Using OR in Conditional Statements
The or operator is commonly used in if statements to check multiple conditions.
Example 1: OR with If Statements
def check_number(a):
if a % 5 == 0 or a % 3 == 0:
print(f"{a} is a multiple of 3 or 5")
else:
print(f"{a} is not a multiple of 3 or 5")
check_number(10) # Output: 10 is a multiple of 3 or 5
check_number(22) # Output: 22 is not a multiple of 3 or 5
check_number(9) # Output: 9 is a multiple of 3 or 5 10 is a multiple of 3 or 5
Example 2: Multiple Valid Inputs
def answer():
ans = 'yes' # Simulating user input
if ans.lower() == 'yes' or ans.lower() == 'y':
print(f'Positive answer: {ans}')
elif ans.lower() == 'no' or ans.lower() == 'n':
print(f'Negative answer: {ans}')
else:
print('Invalid input')
answer() Positive answer: yes
This pattern allows checking multiple valid inputs for the same condition.
Chaining Multiple OR Operations
You can chain multiple or operators together to check if a variable matches any value.
Example 1: Chaining OR Operators
# Check if variable matches any value
user_role = 'admin'
if user_role == 'admin' or user_role == 'moderator' or user_role == 'editor':
print('Access granted')
else:
print('Access denied') Access granted
Example 2: Better Alternative Using 'in'
# Better alternative using 'in' operator
user_role = 'admin'
if user_role in ['admin', 'moderator', 'editor']:
print('Access granted')
else:
print('Access denied') Access granted
Using the in operator is often more readable when checking membership in multiple values.
OR vs Bitwise OR (|)
The logical or operator works with boolean expressions, while the bitwise | operator performs bit-level operations on integers.
Logical OR:
# Logical OR
a = True or False
print(a) True
Bitwise OR (works with integers):
# Bitwise OR (works with integers)
x = 10 # Binary: 1010
y = 4 # Binary: 0100
result = x | y # Binary: 1110
print(result) 14
Common Use Cases
Use Case 1: Input Validation
def validate_age(age):
if age < 0 or age > 150:
return "Invalid age"
return "Valid age"
print(validate_age(25)) # Output: Valid age
print(validate_age(-5)) # Output: Invalid age
print(validate_age(200)) # Output: Invalid age Valid age
Use Case 2: Default Values
def greet(name):
# Use default if name is empty or None
display_name = name or "Guest"
print(f"Hello, {display_name}!")
greet("Alice") # Output: Hello, Alice!
greet("") # Output: Hello, Guest!
greet(None) # Output: Hello, Guest! Hello, Alice! Hello, Guest! Hello, Guest!
Use Case 3: Permission Checking
def can_access_resource(user):
has_subscription = user.get('subscription', False)
is_admin = user.get('admin', False)
if has_subscription or is_admin:
return "Access granted"
return "Access denied"
user1 = {'name': 'John', 'subscription': True}
user2 = {'name': 'Jane', 'admin': True}
user3 = {'name': 'Bob'}
print(can_access_resource(user1)) # Access granted
print(can_access_resource(user2)) # Access granted
print(can_access_resource(user3)) # Access denied Access granted Access granted Access denied
Common Mistakes to Avoid
Mistake 1: Confusing OR with AND
x = 5
# Wrong: This doesn't work as intended
# if x == 3 or 4 or 5: # Always True because 4 and 5 are truthy
# print("Match")
# Correct
if x == 3 or x == 4 or x == 5:
print("Match")
# Better
if x in [3, 4, 5]:
print("Match") Mistake 2: Expecting Boolean Return
# OR doesn't always return boolean
result = 0 or []
print(result) # Output: [] (not False)
print(type(result)) # Output:
# Use bool() for explicit boolean
result = bool(0 or [])
print(result) # Output: False Best Practices
Practice 1: Use 'in' Operator When Checking Membership
# Less readable
if user_role == 'admin' or user_role == 'moderator' or user_role == 'editor':
print('Access granted')
# More readable - prefer 'in' operator
if user_role in ['admin', 'moderator', 'editor']:
print('Access granted') Prefer <code>in</code> operator when checking membership in multiple values
Practice 2: Leverage Short-Circuit Evaluation
# Put the most likely to be True condition first
def quick_check():
return True
def slow_operation():
return False
if quick_check() or slow_operation():
print("At least one is True") Use short-circuit evaluation for performance optimization
Practice 3: Use Parentheses for Complex Conditions
# Less readable
if age >= 18 and has_license or is_supervised and age >= 16:
allow_driving()
# More readable with parentheses
if (age >= 18 and has_license) or (is_supervised and age >= 16):
allow_driving() Use parentheses for complex conditions to improve readability
Practice 4: Avoid Mixing Logical and Bitwise Operators
# Clear intent
if (x > 0 or y > 0):
print("At least one is positive")
# Avoid confusion
# if x > 0 | y > 0: # This is bitwise OR, not logical OR! Avoid mixing logical and bitwise operators without clear intent
Try it Yourself
Practice what you've learned by modifying the code below. Try changing the values and conditions to see different outputs!
// Click "Run Code" to see results
Related Topics
Frequently Asked Questions
What is the difference between 'or' and '||' in Python?
Python uses the keyword or for logical OR operations. The symbol || is used in other languages like C, Java, and JavaScript, but it will cause a SyntaxError in Python.
Does the or operator evaluate both conditions?
Not always. Python uses short-circuit evaluation—if the first condition is True, the second condition is not evaluated because the result is already known to be True.
Can I use or with more than two conditions?
Yes, you can chain multiple conditions: if a or b or c or d:. At least one condition must be True for the expression to evaluate to True.
What is the precedence of or compared to and?
The and operator has higher precedence than or. This means a or b and c is evaluated as a or (b and c). Use parentheses for clarity.
How do I use or for default values?
You can use or to provide default values: name = user_input or "Guest". If user_input is falsy (empty, None, etc.), it will use "Guest".
Can I use or with non-boolean values?
Yes. Python evaluates values in boolean context. or returns the first truthy value, or the last value if all are falsy. Use bool() if you need an explicit boolean.