The or Operator in Python: Complete Guide with Examples

Python or operator explained

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 is ; otherwise, the result is falsy if all operands are falsy.

You’ll often see or paired with , 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 , the or operator returns True if either expression is True. For example, these all return True:

  • True or False

  • False or True

  • True 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”:

python
age = 42name = "Maria"print((age > 35) or (name == "Steve"))# Expected output:# True

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:

python
age = 19name = "Hayden"num_pets = 0print((age > 35) or (name == "Steve") or (num_pets >= 1))# Expected output:# False

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:

  • None

  • 0, 0.0, or 0j

  • '' (empty string)

  • [], {}, (), or set() (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
print(0 or 1)print(12 or 21)print(0 or [])# Expected result:# 1# 12# []

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, 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:

python
values = [1, 2, 3, 4, 5]for value in values:    if (value % 2 == 0) or (value % 5 == 0):        print(f"{value} works!")    else:        print(f"{value} is not allowed.")# Expected result:# 1 is not allowed.# 2 works!# 3 is not allowed.# 4 works!# 5 works!

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:

python
age = -1  # Start from an invalid age to trigger the loopwhile age < 0 or age > 125:    age = int(input("Enter your age: "))# Expected result:# Enter your age: 300# Enter your age: -21# Enter your age: 67

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:

python
user_name = input("Username: ") or "Guest"print(f"Welcome, {user_name}!")# Expected result:# Username: # Welcome, Guest!

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

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:

python
def is_divisible_by_two(x):    print(f"Checking if {x} is divisible by 2")    return x % 2 == 0def is_divisible_by_five(x):    print(f"Checking if {x} is divisible by 5")    return x % 5 == 0value = 10print(is_divisible_by_two(value) or is_divisible_by_five(value))# Expected result:# Checking if 10 is divisible by 2# 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:

python
x = 2print(x == 1 or 2)# Expected return:# 2

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

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. and 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:

python
import pandas as pddf = pd.DataFrame({    "age": [42, 19, 27],    "name": ["Maria", "Hayden", "Steve"]})print((df["age"] > 35) or (df["name"] == "Steve"))# Expected result:# ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()

Instead of the or operator, you need |, the or bitwise operator, which operates .

python
import pandas as pddf = pd.DataFrame({    "age": [42, 19, 27],    "name": ["Maria", "Hayden", "Steve"]})print((df["age"] > 35) | (df["name"] == "Steve"))# Expected result:# 0     True# 1    False# 2     True

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:

Join the Community

roadmap.sh is the 6th most starred project on GitHub and is visited by hundreds of thousands of developers every month.

Rank  out of 28M!

364K

GitHub Stars

Star us on GitHub
Help us reach #1

+90kevery month

+2.8M

Registered Users

Register yourself
Commit to your growth

+2kevery month

50K

Discord Members

Join on Discord
Join the community

RoadmapsGuidesFAQsYouTube

roadmap.shby@nilbuild

Community created roadmaps, best practices, projects, articles, resources and journeys to help you choose your path and grow in your career.

© roadmap.sh·Terms·Privacy·

ThewNewStack

The top DevOps resource for Kubernetes, cloud-native computing, and large-scale development and deployment.