Guide to the Python or Operator

Guide to the Python or Operator

Introduction

The or operator is one of the three existing logical operators in Python (and, or, not), which perform a logical evaluation of the passed operands.

In simple terms, when two operands are passed, it will decide whether the final value of the created logical expression is True or False. The mechanism used to evaluate the value of the final expression is based on the set of rules known as Boolean algebra.

In this guide, we'll cover the or operator in Python as well as its most common use cases.

or Operator Basics

Python's or operator just performs logical disjunction on the two provided operands. Assuming that the operands are simply two Boolean values, the rule on how to use the or operator is pretty straight-forward:

If either one of two operands has the value True, the whole expression has the value True. In all other cases, the whole expression has the value False.

Now let's take a look at the truth table of the or operator:

Operand 1 Operand 2 OR Expression Value
True True True
True False True
False True True
False False False

This table describes the law of logical disjunction. By looking at this table, we can see that the or operator produces False as the result only if both of the operands are False as well.

All of this leads us to the concept of lazy evaluation. A mechanism used to optimize calculations of mathematical operations. In this particular case, it is used to speed up the process of evaluating Boolean expressions with the or operator.

We already know that an or expression results in a True value if either of its two operands is True. Therefore, in a Boolean expression consisting of multiple operands, it is completely unnecessary to evaluate each one of them individually.

It's enough just to read the values of operands one after the other. When we come across a True for the first time, we can safely just ignore all of the other operands and just evaluate the whole expression as True.

On the other hand, if there is no operand with the value True, we must evaluate the whole expression with the value False. That is the basic principle of lazy evaluation - don't evaluate if you don't have to.

Using or on Boolean Variables

The or operator in Python is used to evaluate two of its operands. In this section, we'll focus on the case where both of the operands have Boolean values. In some cases, the or operator can be used with non-Boolean values, which we'll discuss in the following sections.

Let's take a look at how to use the or operator with two Boolean values:

# Two Boolean values
result1 = True or False # Expected to be `True`
result2 = False or False # Expected to be `False`

print('R1:', result1)
print('R2:', result2)

In this example, we can see how the or operator evaluates expressions consisting only of simple Boolean values. As described in the previous sections, this piece of code will have the following output:

R1: True
R2: False

In the previous example, we've named Boolean expressions result1 and result2. That way, we've created two Boolean variables with values True and False, respectively.

Those two variables can be used as the operands of another Boolean expression and, therefore, could be considered as subexpressions of the more complex Boolean expression. That's the general principle used to build more complex Boolean expressions layer by layer:

result3 = result1 or result2 # `True` or `False` <=> `True`
result4 = result3 or True # `True` or `True` <=> `True`

print('R3:', result3)
print('R4:', result4)

As expected, this will output:

R3: True
R4: True

result4 is a complex Boolean expression consisting of multiple subexpressions and Boolean values. Let's take a look at the process of unfolding it:

1. result4 = result3 or True
2. result4 = (result1 or result2) or True
3. result4 = ((True or False) or (False or False)) or True

Based on the associative law for the or operator, we know that the order in which we apply the operator doesn't have an impact on the value of the Boolean expression, so there is no need for brackets. Therefore, we can transform result4 one step further by deleting all of the brackets:

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

 result4 = True or False or False or False or True

Using or on Non-Boolean Variables

The or operator in Python can also be used with variables other than Boolean. You can even mix and match Boolean variables with non-Boolean variables. In this section, we'll go over some examples that illustrate the usage of the or operator with variables of different data types.

Generally speaking, any object or a variable in Python is considered to be True unless its class has a predefined __bool__() method that returns False or a __len__() method that returns 0.

In simple terms that means that only objects considered to be False are those which are predefined to be False or those which are empty - empty lists, tuples, strings, dictionaries... The Official Python documentation gives us the list of some of the most common built-in objects considered to be False:

  • Constants defined to be false: None and False.
  • Zero of any numeric type: 0, 0.0, 0j, Decimal(0), Fraction(0, 1)
  • Empty sequences and collections: '', (), [], {}, set(), range(0)

Note: These are also known as Falsy Values - the ones you'd intuitively be able to reduce to a False boolean value. The opposite values are Truthy Values.

Another very important fact is that the or operator in this case returns the actual object, not the True/False value of the object.

Let's take a look at the example that illustrates mentioned behavior:

exp = {} or 'This is a string'

As stated before, the first operand - {} (empty dictionary) is considered to be False and the second operand - 'This is a string' (not an empty string) is considered to be True. This means that the previous expression is implicitly transformed to:

# exp = False or True

Here, exp is evaluated to True. But, when we try to print the original exp value, instead of True, the output will be:

'This is a string'

This example illustrates the case when the or operator returns the object itself instead of its True/False value. To sum this behavior up, we can illustrate it with the altered (truth) table of the or operator:

object1 (value) object2 (value) object1 `or` object2 (return value)
True True object1
True False object1
False True object2
False False object2

This also applies when we combine usual Boolean values and objects in Boolean expressions.

If the expression contains at least one value that is considered to be True, the value of the expression is True, but the return value can vary based on the first True element in it.

If the first True operand to be found in the expression is a simple Boolean value, the return value will be True, but if the first True element is some sort of an object, the return value will be that object itself. For example, the following expression will return True:

0 or True 

And the following expression will return [1, 2, 3], which is the first True operand found:

False or [1, 2, 3]

On the other hand, if a Boolean expression is False, meaning that no True operand was found, its return value will be its last operand, either object or False:

{} or 0.0 or [] or False or ()
# Output >> ()

Conclusion

In this guide, we've explained the usage of the or operator in Python. We've introduced the syntax in Python and described how the or operator evaluates Boolean expressions and how it determine the proper return value based on the operands.

Besides its primary usage for evaluating Boolean expressions, the or operator can also be pretty useful in some other use cases.

Its features make it a good choice when you need to set default values for some variables or a default return value of a function and much more, but those special use cases are far beyond the scope of this article, so we'll let you explore all the use cases that the or operator can be utilized in.

Last Updated: December 16th, 2021
Was this article helpful?

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

Project

Real-Time Road Sign Detection with YOLOv5

# python# machine learning# computer vision# pytorch

If you drive - there's a chance you enjoy cruising down the road. A responsible driver pays attention to the road signs, and adjusts their...

David Landup
David Landup
Details
Project

Data Visualization in Python: The Collatz Conjecture

# python# matplotlib# data visualization

The Collatz Conjecture is a notorious conjecture in mathematics. A conjecture is a conclusion based on existing evidence - however, a conjecture cannot be proven....

David Landup
Jovana Ninkovic
Details

© 2013-2022 Stack Abuse. All rights reserved.

DisclosurePrivacyTerms