How to use 'or' in Python
Master Python's 'or' operator. This guide covers various methods, pro tips, real-world applications, and how to debug common errors.

Python's or operator is a fundamental tool to control program flow and evaluate conditions. It allows you to execute code when at least one of several expressions is true.
In this article, you'll explore techniques for the or operator, from basic use to advanced short-circuiting. We'll cover real-world applications, common pitfalls, and debugging tips to help you write cleaner code.
Basic usage of the or operator
result1 = True or False
result2 = False or False
print(f"True or False: {result1}")
print(f"False or False: {result2}")--OUTPUT--True or False: True
False or False: False
The or operator works by checking for the first True value in a sequence. It returns True if any expression is true and only returns False if all are false.
True or FalseisTruebecause the first operand satisfies the condition.False or FalseisFalsebecause no true values are found.
This efficient evaluation, where the operator stops once the outcome is known, is a key feature that makes your code more performant.
Using the or operator with variables and conditions
Building on those fundamentals, the or operator becomes even more powerful when applied to variables and conditional statements to control your program's flow.
Using or with variable comparisons
x = 5
y = 10
is_valid = x > 10 or y > 8
print(f"x > 10 or y > 8: {is_valid}")
condition = x < 3 or y < 3
print(f"x < 3 or y < 3: {condition}")--OUTPUT--x > 10 or y > 8: True
x < 3 or y < 3: False
The or operator is perfect for checking if at least one of several variable comparisons is true. It evaluates expressions from left to right and stops at the first True condition it finds.
- For the
is_validvariable,x > 10is false, but sincey > 8is true, the entire expression evaluates toTrue. - In the second case, both
x < 3andy < 3are false. Because no true condition is found, the result isFalse.
Using or in conditional statements
age = 25
income = 40000
if age > 18 or income > 50000:
print("Eligible for premium membership")
else:
print("Not eligible for premium membership")--OUTPUT--Eligible for premium membership
The or operator is a natural fit for if statements, letting you create flexible conditions. In this scenario, the program checks for premium membership eligibility by evaluating if age > 18 or income > 50000.
- The first condition,
age > 18, is true, so the entire expression is immediately confirmed asTrue. - The program doesn't need to check
income > 50000. It proceeds to run the code inside theifblock, granting eligibility.
Short-circuit evaluation with or
def check(message, return_value):
print(f"Checking: {message}")
return return_value
result = check("First condition", True) or check("Second condition", False)
print(f"Result: {result}")--OUTPUT--Checking: First condition
Result: True
The or operator uses a clever trick called short-circuiting. It evaluates expressions from left to right and stops the moment it finds a True value, because the outcome is already known. This makes your code more memory-efficient by avoiding unnecessary work.
- In the example, the first function call,
check("First condition", True), returnsTrue. - Since the first part of the expression is true, Python skips running
check("Second condition", False)entirely. - This is why "Checking: Second condition" is absent from the output—the second function was never called.
Advanced uses of the or operator
Building on its short-circuiting behavior, you can make the or operator even more versatile by combining it with other operators and non-boolean values. This flexibility is one reason vibe coding in Python feels so natural.
Combining or with other logical operators
a, b, c = True, False, True
# Combining and, or, and not
result1 = (a and b) or (not b and c)
result2 = a and (b or c)
print(f"(True and False) or (not False and True): {result1}")
print(f"True and (False or True): {result2}")--OUTPUT--(True and False) or (not False and True): True
True and (False or True): True
You can create complex conditions by combining the or operator with and and not. Python follows a specific order of operations: not is evaluated first, then and, and finally or. You can use parentheses to control this order, which also makes your code much easier to read.
- In the first example,
(a and b)isFalse, but(not b and c)isTrue. Theoroperator then makes the whole expressionTrue. - For
result2, the parentheses ensure(b or c)is evaluated first, resulting inTrue. Theandoperator then combinesawith this result, also yieldingTrue.
The or operator with different data types
# or returns the first truthy value or the last value
result1 = 0 or "" or [] or "Hello"
result2 = 42 or "Python"
result3 = "" or 0 or None
print(result1, result2, result3)--OUTPUT--Hello 42 None
The or operator doesn't just return True or False. It returns the first value in a sequence that Python considers "truthy." This is a powerful feature for setting default values or simplifying your logic.
- In the first example,
orskips the falsy values0,"", and[]until it finds the truthy string"Hello"and returns it. - For
result2, the expression short-circuits. Since42is truthy, it's returned immediately without evaluating"Python". - If all values are falsy, as with
result3, the operator returns the last value in the chain, which isNone.
Using or for default values
# Setting default values with or
user_name = ""
display_name = user_name or "Guest"
config = {"timeout": 0}
timeout = config.get("timeout") or 30
print(f"Welcome, {display_name}! Timeout: {timeout}s")--OUTPUT--Welcome, Guest! Timeout: 30s
The or operator offers a concise way to assign default values. It returns the first truthy value in an expression, which is useful for handling optional or empty variables without a full if statement.
- Since
user_nameis an empty string (""), which is falsy, the expression defaults to the next value. As a result,display_nameis set to"Guest". - This pattern is also useful for configurations. The value for
timeoutis0, another falsy value, so the expression assigns the default of30instead.
Move faster with Replit
Replit is an AI-powered development platform that comes with all Python dependencies pre-installed, so you can skip setup and start coding instantly. While mastering operators like or is key, you can move from piecing together techniques to building complete apps with Agent 4. It takes your idea and builds a working product, handling the code, databases, APIs, and deployment from a simple description.
Instead of building from scratch, you can describe the final application you want. For example, Agent 4 can build:
- A user profile that displays a "Guest" name if the
user_namevariable is empty. - An eligibility checker that approves a loan if an applicant has good credit
ora qualified co-signer. - A configuration utility that loads a setting from an environment variable,
ora config file if the variable isn't found.
Simply describe your app, and Replit will write the code, test it, and fix issues automatically, all within your browser.
Common errors and challenges
While the or operator is powerful, a few common pitfalls involving precedence, list checks, and falsy values can lead to unexpected behavior. Learning effective debugging techniques helps you catch these issues early.
Fixing operator precedence with or
A frequent pitfall is assuming the or operator distributes an equality check across multiple values. Python evaluates if x == 5 or 10 or 15 by checking the truthiness of 10 and 15 on their own, which are always True. This leads to unexpected results, as the code below demonstrates.
x = 5
# Intended: Check if x equals 5, 10, or 15
if x == 5 or 10 or 15:
print("x is either 5, 10, or 15")
else:
print("x is not 5, 10, or 15")
The condition passes because Python treats the number 10 as a truthy value, so the expression short-circuits to True. This logic is flawed because it never compares x to 10 or 15. Here's how to fix it.
x = 5
# Correct way to check if x equals any of these values
if x == 5 or x == 10 or x == 15:
print("x is either 5, 10, or 15")
else:
print("x is not 5, 10, or 15")
The corrected code works because it explicitly compares the variable to each value in the chain. This is a common pitfall when you're checking if a variable matches one of several options.
- Instead of
x == 5 or 10, you must write the full comparison:x == 5 or x == 10. - This prevents Python from simply evaluating the truthiness of the number
10, ensuring your logic is sound.
Using or versus the in operator
A similar issue arises when checking if an item belongs to a group of values. Using or is a common but flawed approach because of Python's truthiness rules. The in operator provides a much cleaner solution. See this error in action.
# Trying to check if fruit is apple, banana, or orange
fruit = "grape"
if fruit == "apple" or "banana" or "orange":
print(f"{fruit} is in our basket")
else:
print(f"{fruit} is not in our basket")
The condition always passes because Python evaluates the string "banana" as a truthy value, causing the expression to short-circuit. This means the check is flawed. See how to fix this with a much cleaner approach.
# Correct way to check membership
fruit = "grape"
if fruit in ["apple", "banana", "orange"]:
print(f"{fruit} is in our basket")
else:
print(f"{fruit} is not in our basket")
The corrected code uses the in operator to properly check if fruit is present within the list. This is the idiomatic Python way to test for membership. It's more readable and avoids the logical error caused by how the or operator handles truthy values.
- Use the
inoperator whenever you need to check if an item exists in a collection like a list, tuple, or set. - This prevents accidentally creating a condition that is always
True.
Handling falsy values with or
Using the or operator for defaults can backfire when a valid value is falsy, like the number 0. This can lead to unintended behavior where your code ignores a legitimate setting. The following example shows this problem in action.
# Setting default values with or
user_settings = {"volume": 0, "brightness": 50}
volume = user_settings.get("volume") or 100
brightness = user_settings.get("brightness") or 75
print(f"Volume: {volume}, Brightness: {brightness}")
The volume is incorrectly set to 100. Because the intended value, 0, is falsy, the or operator discards it and assigns the default instead. The code below demonstrates a more reliable approach to this problem.
# Correctly handling falsy values that might be valid
user_settings = {"volume": 0, "brightness": 50}
volume = user_settings.get("volume") if "volume" in user_settings else 100
brightness = user_settings.get("brightness") if "brightness" in user_settings else 75
print(f"Volume: {volume}, Brightness: {brightness}")
The corrected code avoids the falsy value trap by using a conditional expression. It explicitly checks if a key exists in the dictionary rather than relying on the or operator's truthiness evaluation. This ensures that a legitimate but falsy value, like 0 for volume, is preserved instead of being replaced by a default.
- Use this approach whenever
0,False, or empty strings are valid inputs for your program. - It makes your code more robust and predictable.
Real-world applications
With those common errors fixed, you can confidently use the or operator for practical tasks like form validation and configuration fallbacks.
Form validation with the or operator
The or operator is a great tool for checking if any required form fields are empty, letting you quickly validate user input.
username = "john_doe"
email = "" # Empty email
password = "password123"
is_invalid = not username or not email or not password
if is_invalid:
print("Form submission failed: All fields are required")
else:
print("Form submitted successfully")
This logic hinges on the interplay between the not and or operators. The not operator flips the truthiness of each variable, turning truthy, non-empty strings into False and falsy, empty ones into True.
- In this case,
not usernameisFalse, but sinceemailis empty,not emailevaluates toTrue. - The
orexpression short-circuits as soon as it hits the firstTruevalue, making the entire conditionTrue.
As a result, is_invalid is set to True, and the code confirms that a required value was missing, triggering the failure message.
Using or for configuration fallbacks
The or operator lets you create a robust fallback system by checking for settings in a prioritized order, such as from environment variables before a config file.
# Simulate different config sources
env_vars = {"DEBUG": "True"} # Environment variables
config_file = {"app.name": "MyApp", "app.timeout": 30} # Config file
app_name = env_vars.get("APP_NAME") or config_file.get("app.name") or "DefaultApp"
timeout = env_vars.get("TIMEOUT") or config_file.get("app.timeout") or 60
debug = env_vars.get("DEBUG") == "True" or config_file.get("app.debug") or False
print(f"App: {app_name}, Timeout: {timeout}, Debug: {debug}")
This code uses the or operator's short-circuiting to pull settings from different sources. The expression is evaluated from left to right, and Python assigns the first truthy value it encounters.
- For
app_nameandtimeout, the code checksenv_varsfirst. Since it finds nothing, it moves toconfig_fileand assigns the values found there. - The
debugvariable is set toTrueimmediately because the first condition,env_vars.get("DEBUG") == "True", is met, so the rest of the expression is ignored.
Get started with Replit
Turn what you've learned into a real tool. Tell Replit Agent to build "a script that grants access if a user is an admin or has a special pass" or "a config loader that uses a default value if an environment variable is missing".
It will write the code, test for errors, and deploy the app from your description, letting you focus on your final product. Start building with Replit.
Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.
Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.



