Skip to content

How to Use the 'or' Boolean Operator in Python

CodeMDD.io

Introduction

Python is a versatile programming language that offers a wide range of features and tools to developers. One of these features is the ability to use Boolean operators, which allow you to test conditions and make decisions in your code. In this tutorial, we will explore the “or” Boolean operator in Python and learn how to effectively use it.

The “or” operator in Python evaluates two expressions and returns True if at least one of the expressions is True. Otherwise, it returns False. This operator is commonly used in scenarios where you want to check if one or both conditions are met.

How the Python or Operator Works

The “or” operator in Python can be used with both Boolean expressions and common objects. Let’s explore these use cases in more detail:

Using or with Boolean Expressions

When using the “or” operator with Boolean expressions, the operator evaluates the expressions from left to right and stops as soon as it encounters the first True value. If all expressions are evaluated and none of them are True, the operator returns False.

Example:

x = 5
y = 10
z = 20
result = (x > y) or (x == y) or (y < z)
print(result)

Output:

True

In this example, result will be True because the second expression (x == y) evaluates to False, but the third expression (y < z) evaluates to True.

Using or with Common Objects

The “or” operator in Python can also be used with common objects that are not Boolean values. Python has a concept called “truthiness” where it evaluates non-Boolean objects as either True or False.

When using the “or” operator with objects, Python evaluates the objects from left to right and stops as soon as it encounters the first object that is considered “truthy”. If all objects are evaluated and none of them are “truthy”, the operator returns the last evaluated object.

Example:

name = "John"
age = 25
is_employed = False
result = name or age or is_employed
print(result)

Output:

John

In this example, result will be the value of name because it is considered “truthy” (i.e., it is not an empty string or a value of False or None).

Mixing Boolean Expressions and Objects

You can also mix Boolean expressions and non-Boolean objects when using the “or” operator in Python.

Example:

is_student = True
favorite_color = ""
result = is_student or (name and favorite_color)
print(result)

Output:

True

In this example, result will be True because the first expression is_student is True and the second expression (name and favorite_color) returns an empty string, which is considered “falsy”.

Short-Circuit Evaluation

One important behavior of the “or” operator in Python is short-circuit evaluation. Short-circuit evaluation means that if the first expression is True, the second expression is not evaluated because the result of the “or” operation is already determined. This can be useful when you have expressions that may have side effects.

Example:

is_logged_in = True
result = is_logged_in or login_user()
print(result)

Output:

True

In this example, the function login_user() is not called because the first expression is_logged_in is True, and the result of the “or” operation is already determined to be True.

Section Recap

In this section, we have covered the basics of the “or” operator in Python. We learned that the “or” operator evaluates expressions from left to right and returns True if at least one expression is True. We also explored how the “or” operator can be used with both Boolean expressions and common objects.

Boolean Contexts

In Python, there are several contexts where Boolean values are expected. These contexts include if statements and while loops. Let’s explore these contexts in more detail:

if Statements

In an if statement, the condition expression is evaluated, and if the result is True, the corresponding block of code is executed. Otherwise, the block of code is skipped.

Example:

x = 10
if x > 5 or some_function():
print("x is greater than 5")

In this example, if the first expression x > 5 is True, the second expression some_function() is not evaluated because of short-circuit evaluation. If the first expression is False, the second expression will be evaluated.

while Loops

Similarly to if statements, while loops also expect a Boolean expression as a condition. The loop will continue executing as long as the condition is True. Once the condition becomes False, the loop will terminate.

Example:

x = 5
while x < 10 or some_function():
print("x =", x)
x += 1

In this example, if the first expression x < 10 is True, the second expression some_function() is not evaluated because of short-circuit evaluation. If the first expression becomes False, the second expression will be evaluated.

Non-Boolean Contexts

In addition to Boolean contexts, Python allows you to use non-Boolean objects in certain situations where a Boolean value is expected. Let’s explore some of these contexts:

Default Values for Variables

In Python, you can provide default values for variables using the “or” operator. If the first expression is considered “falsy”, the second expression (the default value) will be used instead.

Example:

name = None
result = name or "John Doe"
print(result)

Output:

John Doe

In this example, since name is None, it is considered “falsy”, so the “or” operator uses the second expression "John Doe" as the result.

Default return Values

When defining functions in Python, you can use the “or” operator to provide default return values. If the first expression is considered “falsy”, the second expression (the default return value) will be returned.

Example:

def divide(x, y):
if y == 0:
return None
return x https://codemdd.io/ y or 0
result = divide(10, 2)
print(result)

Output:

5.0

In this example, if y is 0, the first expression x https://codemdd.io/ y evaluates to None, so the “or” operator uses the second expression 0 as the default return value.

Mutable Default Arguments

In Python, when defining a function, you can provide default values for arguments. However, you need to be careful when using mutable objects (e.g., lists, dictionaries) as default arguments. If you modify the mutable object in the function, the modifications will persist across multiple function calls.

Example:

def add_item(item, lst=[]):
lst.append(item)
return lst
result1 = add_item(1)
print(result1)
result2 = add_item(2)
print(result2)

Output:

[1]
[1, 2]

In this example, since lst is a mutable object, the modifications made in the first function call persist in subsequent function calls. To avoid this behavior, you can use the “or” operator to provide a new empty list as the default argument.

Zero Division

When performing division in Python, you need to handle the scenario where the denominator is 0. In these cases, you can use the “or” operator to provide a default result.

Example:

x = 10
y = 0
result = x https://codemdd.io/ (y or 1)
print(result)

Output:

10.0

In this example, since y is 0, the first expression (y or 1) evaluates to 1, so the division is performed correctly.

Multiple Expressions in lambda

In Python, you can use lambda functions to create small, anonymous functions. The “or” operator can be used to combine multiple expressions in a lambda function.

Example:

numbers = [1, 2, 3, 4, 5]
result = list(map(lambda x: x if x < 3 else (x * 2) or x, numbers))
print(result)

Output:

[1, 2, 6, 8, 10]

In this example, the lambda function uses the “or” operator to return x if x is less than 3. Otherwise, it multiplies x by 2 and returns the result. If the multiplication evaluates to 0, the lambda function returns x instead.

Conclusion

In this tutorial, we explored the “or” Boolean operator in Python and learned how to effectively use it in various scenarios. We covered how the “or” operator works with both Boolean expressions and common objects, as well as its behavior in Boolean and non-Boolean contexts.

By mastering the “or” operator in Python, you will have a powerful tool in your programming arsenal to create expressive and concise code. Remember to take advantage of short-circuit evaluation and understand the truthiness of objects when using the “or” operator.

Continue practicing and experimenting with the “or” operator in Python to enhance your understanding and proficiency in using it. Happy coding! CodeMDD.io