The or Operator in Python: Complete Guide with Examples

To be, or not to be? Heads or tails? For here or to go?
Our world constantly asks us to decide and relies on the word "or" to indicate our choices. Python also uses or, but as a logical operator that evaluates the truthiness of its operands to determine which value to return.
In this article, we’ll walk you through what the or operator is, what it does in Python, and several practical use cases to see it in action. You’ll also learn about some common or “gotchas” to make sure your code isn’t erroneous or unclear. Let’s begin by introducing you to or in Python.
What is or in Python?
Like many other languages, Python uses or as a logical operator. You’ll use it to combine two (or more) expressions into a single logical expression. The overall or expression is True if at least one of its operands is truthy; otherwise, the result is falsy if all operands are falsy.
You’ll often see or paired with Boolean expressions, but it works with non-Boolean objects as well. For efficiency, or uses short-circuit evaluation, meaning that it stops as soon as it finds a truthy operand. Now we’ll show you the basic syntax of or so that you can start using it in your own code.
Basic Syntax for Booleans
Generally, you’ll write expression1 or expression2 when using or. Python evaluates the left expression first, and only processes the right expression if needed. When working with Booleans, the or operator returns True if either expression is True. For example, these all return True:
True or FalseFalse or TrueTrue or True
The or operator returns False only if both expressions are False:
False or False
or for Boolean Expressions
Boolean operations allow you to combine or modify Boolean expressions, and or is one of the most commonly used. This code checks if either age is greater than 35 or name is “Steve”:
Here, name is not “Steve,” but the output is still True since age is greater than 35. Notice that we enclosed each condition in parentheses for readability. They’re optional in this example, but they can make complex logical expressions easier to understand.
You may also chain multiple conditions together with more than one or. Python checks each one from left to right and stops as soon as one evaluates to True. If none of the conditions are True, it processes the entire expression and returns False. This code prints False since none of the three conditions evaluate to True:
How the or Operator Works with Non-Boolean Values
Unlike some other languages that require Boolean operands, Python allows the or operator to work on non-Booleans by testing for truthiness.
Besides False, Python also considers the following to be falsy:
None0,0.0, or0j''(empty string)[],{},(), orset()(empty collections)range(0)
It regards nearly every other value as truthy.
When working with non-Booleans, the or operator evaluates expressions from left to right and returns the first truthy operand. It gives back the last value if all operands are falsy. Here’s a few examples demonstrating or for non-Booleans:
Python evaluates both 0 and the empty list in a Boolean context and finds them to be falsy. Perhaps surprising upon first glance, the or operator’s behavior proves particularly useful to set default values, as you’ll see in the upcoming practical use cases.
Practical Use Cases
So far, you’ve learned the basics of what or is and what it can do. In this section, we’ll show you a few practical coding examples that feature or. Look for or operating on both Boolean and non-Boolean values in what follows.
if Statements with Multiple Conditions
In Python, if statements use logic to pass control to various code blocks depending on conditional outcomes. You’ll commonly see the or operator to combine multiple conditions, executing code when at least one condition is true.
This code prints a positive message for numbers that are even or divisible by 5:
while Loops Including Conditional Statements
while loops repeatedly execute a code block as long as a given condition remains True. Just like if statements, you can use logical operations in while loops.
This example highlights validating user inputs before proceeding. The while loop continues to ask the user to enter their age until their input falls within the valid range of 0 to 125:
Default Values
You can also use or to set default values for Python programs that may have missing user input or unset optional configurations. Since the or operator returns the first value that is truthy for non-Boolean operands, you can include a fallback value as the final operand in your or expression to serve as a default.
For example, you may use “Guest” as a default user name if one isn’t provided:
If the user simply presses Enter without typing anything, the input is a blank string (''), which is falsy in a Boolean context. The or operator then sets user_name to "Guest" because empty strings are falsy and "Guest" is the first truthy operand.
or is part of a common pattern to set default values for user input, environment variables, function arguments, dictionary lookups, and configuration settings. With this style, any falsy value triggers the default, not just None. If an empty string, 0, or False is an acceptable input, avoid using or to provide defaults. Explicitly test whether the value is None instead.
Short-Circuit Evaluation
Short-circuit evaluation means Python can stop processing a logical expression as soon as it has enough information to determine the overall result. The or operator uses short-circuiting by processing expressions from left to right and stopping as soon as one expression is truthy. It never checks later expressions if it doesn’t need them.
Notice how this code never even calls the is_divisible_by_five() function because is_divisible_by_two() evaluates to True, which makes the entire or expression True:
With short-circuit evaluation, Python can actually improve its performance for very large datasets or expensive function calls. Placing the expression that is most likely to evaluate to True first often allows Python to skip the remaining expressions entirely. You may also place expensive function calls later in the expression to avoid executing them whenever an earlier expression is truthy.
You’ll likely only see performance gains for extreme amounts of data, database queries, API calls, or complex functions, so continue prioritizing readability over minimal time savings. Nonetheless, understanding short-circuiting can help you write code that’s more efficient and easier to optimize.
Common Pitfalls
You’ve quickly gained skill with or for combining comparisons and processing non-Booleans, but there are a few more potential stumbling blocks to dodge when incorporating or into your code. Read through these common pitfalls to ensure or behaves as expected for you.
Incomplete Comparisons
Say you’d like to check if a variable, x, is equivalent to 1 or 2. The following demonstrates an incomplete comparison with the or operator:
Note that this code does not print True. It correctly checks to see if x == 1. Since that comparison is False, the or operator returns its second operand, 2, which is a truthy value in Python.
To test whether x equals 1 or 2, you’ll need to combine two separate comparisons: x == 1 or x == 2. Better yet, switch to the in membership operator for clarity: x in (1, 2).
Precedence Errors
Operator precedence refers to the order Python processes operators in an expression. The or operator has lower precedence than comparison operators as well as the logical operator and. You can add parentheses at any point to clarify or change the order of evaluation for expressions involving or.
For example, the following two expressions are logically equivalent:
age > 35 or name == "Steve"(age > 35) or (name == "Steve")
Python evaluates the comparison operators (> and ==) before or, so both expressions produce the same result.
Due to operator precedence, Python interprets this expression:
has_password or has_api_key and is_verified
As:
has_password or (has_api_key and is_verified)
Instead of what you may have intended:
(has_password or has_api_key) and is_verified
As a best practice, add parentheses to ensure Python evaluates your multi-operator expressions in your intended order. Even when they aren’t required, parentheses often make your code easier to read.
Confusing or for | in NumPy/Pandas
or is a logical operator in Python. It expects a single truth value for each of its operands. NumPy arrays and pandas Series are highly efficient for storing and handling large amounts of data; however, these objects hold many values, producing multiple Boolean results when compared. Using or with these objects usually results in an error:
Instead of the or operator, you need |, the or bitwise operator, which operates elementwise.
This code correctly returns False or True for each row individually. Also note that each comparison should be enclosed in parentheses here because the | bitwise operator has different precedence than comparison operators.
Wrapping Up
or is a logical operator in Python, useful for combining multiple expressions into a single result. The or operator evaluates operands from left to right and returns the first truthy value or the last value if all are falsy. It also uses short-circuiting to avoid unnecessary evaluations. You’ll find the or operator in if statements, while loops, and to provide default values when working with non-Booleans. Just be sure to avoid incomplete comparisons (e.g. user == "guest" or "test123") and be mindful of operator precedence when including or in your Python code.
Check out the AI Tutor to continue exploring the or operator’s capabilities. This prompt will get you going:
- Python reduce(): The Complete Guide (With Examples)
- Master Python Filter: Syntax, Examples, and Best Practices
- Python Max Int: Understanding Arbitrary Precision Integers
- Python KeyError Exceptions: Causes and Fixes Explained
- Python Null (None): Guide to Missing Values and NoneType
- Python Backend Development: Build Your First API
- Python Backend Frameworks: How to Choose the Right One
- Python Return Multiple Values: 4 Methods & Examples
- Python Multiline Strings: The Complete Guide
- Python not Operator: The Complete Guide to Logical Negation
Kimberly Fessel