"
This article is part of in the series

Python Or Operator

Using Boolean operators is a straightforward way to test conditions that determine the execution flow of your Python programs. 

The or operator in Python is one of the three Boolean operators Python offers. In this brief guide, we'll walk you through how to use the operator. 

How Does "or" Work in Python?

The Boolean or operator allows you to connect 2 Boolean expressions and turn them into a single compound expression. The general logic of the "or" operator is:

If at least one of the two subexpressions in the compound expression is true, the expression is regarded as true. However, if both the subexpressions are false, then the expression is false. 

And this is the long and short of how the Python or operator works. But there's a lot you can do with the operator, as we will discover in the coming sections.

Using Python's "or" with Boolean Expressions

Creating a Boolean expression with "or" requires two subexpressions, and you must follow the syntax below:

expression1 or expression2 

So, if either expression1 or expression2 is True, the entire expression will be evaluated to True. On the other hand, if both subexpressions are False, then the expression is evaluated as False. 

This type of logical evaluation is called "inclusive or," as it accepts either possibility or both. Here's a table summarizing the or operator's behavior in Python:

Result of expression1 Result of expression2 Result of expression1 or expression2
True True True
False True True
True False True
False False False

Let's take a look at some examples that illustrate the functioning of the or operator:

# Example 1
expression1 = 5 != 8  # 5 is not equal to 8, so True
expression2 = 13 <= 12  # 13 is greater than 12, so False

print(expression1)  # Output: True
print(expression2)  # Output: False

result1 = expression1 or expression2
print(result1)  # Output: True

result2 = expression2 or expression1
print(result2)  # Output: True

# Example 2
expression3 = 15 > 20  # 15 is not greater than 20, so False

result3 = expression2 or expression3
print(result3)  # Output: False

As you can see, when a subexpression evaluates to True, any expression it is involved in also evaluates to True. But if two subexpressions are False, then the global result is also False.

Using "or" with Python Objects

For a successful "or" operation in Python, the operands must yield Boolean values as outlined in the table from the previous section. Only under these conditions do they produce a meaningful truth value as the result.

However, Python isn't strict about the values when you use objects as the operands in an "or" operation. It follows a preset list of rules to determine whether an object evaluates to True or False. 

Non-zero numeric values, non-empty dictionaries, and non-empty sequences are objects that Python's "or" evaluates to True. On the other hand, the number 0, empty sequences, and the "None" and "False" values are evaluated to be False. 

Moreover, if Python objects are used in the Boolean "or" operation, then Python returns a True or False object, not True or False values

The predictable bit of this operation is that the objects' truth value is determined using the same logic as indicated in the table in the previous section. 

Convenient, right?

It's noteworthy that Python doesn't constrain the results of "or" operations to Boolean objects. When doing an "or" operation in Python, it will either return the first object that evaluates to True or the final object in the expression, even if it is False. 

Here are some examples of Python applying the "or" operation on objects:

# Example 1
result1 = 10 or 7
print(result1)  # Output: 10

# Example 2
result2 = 0.0 or 15
print(result2)  # Output: 15

# Example 3
result3 = [] or "Hello"
print(result3)  # Output: "Hello"

# Example 4
result4 = False or [1, 2, 3]
print(result4)  # Output: [1, 2, 3]

The operands on the left (10 and 0.0) are True in the first two examples, so the or operator returns the first operand.

The operands on the left ([] and False) are False in the last two examples. The or operator evaluates both operands and returns the object on the right, which may be either True or False.

Bear in mind that if you need to get "True" or "False" values from a Boolean expression that involves objects, you can use bool(obj). The built-in method will return the appropriate value of the "obj" you supply.

Summing up, Python's "or" returns the first object in the expression that is True, or the last object in the expression whether it's True or False. The following example generalizes this behavior by linking operations into a single expression:

result = a or b or c or d

In this setup, the or operator returns the first True operand encountered or the last one evaluated. Remembering this rule of thumb is key to understanding the functioning of the or operator in Python.

Using Both Objects and Boolean Expressions in "Or" Operations

Python allows you to use both expressions and objects in a single "or" operation. What's interesting is that there are three possible results of such expressions and not two: True, False, and the object being tested. 

Here are the possibilities in table format:

Expression Evaluation Object Evaluation Result of Expression Or Object Operation
True True True
True False True
False False Object
False True Object

Let's see this in action:

# Case 1
result1 = 3 <= 5 or "Hello"
print(result1)  # Output: True

# Case 2
result2 = 8 < 12 or {}  # Using an empty dictionary
print(result2)  # Output: True

# Case 3
result3 = 15 > 20 or "Python"
print(result3)  # Output: "Python"

# Case 4
result4 = 7 > 10 or [1, 2, 3]  # Using a non-empty list
print(result4)  # Output: [1, 2, 3]

 

In these examples:

  • In Case 1, the expression 3 <= 5 is True, so the or operator returns the first true operand, which is the string "Hello."
  • In Case 2, the expression 8 < 12 is True, so the or operator returns the first true operand, which is an empty dictionary {}.
  • In Case 3, both the expression 15 > 20 and the object "Python" are False, so the or operator returns the object on the right, which is the string "Python."
  • In Case 4, the expression 7 > 10 is False, so the or operator returns the object on the right, which is a non-empty list [1, 2, 3].

Short-Circuiting in Python

In some cases, Python can evaluate the truth value of Boolean expressions before evaluating all its subexpressions and objects. 

When you use the "or" operator, Python stops evaluating the subexpressions and objects when it determines any single subexpression is True. Think about it, this expression always evaluates to True:

True or 9 < 5

Of course, this is because the first operand is True; therefore, the second operand's value doesn't matter. When operands end up never being evaluated as a conclusive result has been found, it is referred to as short-circuiting or lazy evaluation.

Setting Default Results in "Or" Operations for Clarity 

Many developers prefer using the "or" operator with a "None" value included as the final subexpression. Here's what this looks like:

expression = exp1 or exp2 or None

If exp1 and exp2 turn out to be False, Python will set the expression variable to None, as it is the last one. Of course, if either of them were True, the expression variable would be set to the first value that was evaluated to True.

You can use this aspect of the "or" operation to assign a default value to variables. You don't have to use None as the default value – you can also use keywords like "default."

Here's what this looks like:

expression = exp1 or default

If exp1 evaluates to True, the "expression" variable would be set to exp1. Otherwise, the expression variable is set to "default."

Interestingly, you can also manipulate the return value of built-in functions using the "or" operator. For example, take the max() and min() functions. These accept iterables as arguments before returning a value, making them the perfect functions to manipulate with "or."

If you supply an empty iterable to either of these functions, Python will throw ValueError. Take a look at this code that bypasses that error:

data = []  # Empty list to test max() and min()

# Attempting max() and min() on an empty list raises a ValueError
try:
    result_max_error = max(data)
except ValueError as ve:
    result_max_error = f"ValueError: {ve}"

try:
    result_min_error = min(data)
except ValueError as ve:
    result_min_error = f"ValueError: {ve}"

print(result_max_error)  # Output: ValueError: max() arg is an empty sequence
print(result_min_error)  # Output: ValueError: min() arg is an empty sequence

# Using the Python or operator to modify this behavior
result_max = max(data or [0])  # Returns 0
result_min = min(data or [0])  # Returns 0

print(result_max)  # Output: 0
print(result_min)  # Output: 0

As you can see, using the "or" operator overrides the default behavior of min() and max(). 

Conclusion

In a nutshell, the Python "or" operator is your trusty sidekick for combining Boolean expressions and objects in a single operation. 

Remember, the entire expression becomes true if there's at least one true element in the mix. Plus, Python is pretty flexible – it doesn't mind working with objects; it'll happily return the first true object or the last one, no matter if it's false.

So, whether you're navigating Boolean expressions, working with objects, or setting defaults for clarity, the "or" operator in Python is here to make your coding journey smoother. 

Practice and add this operator to your coding toolbox, and working out flows of complicated programs will soon be a cakewalk.