or
In Python, the or
keyword is a logical operator that evaluates two Boolean expressions and returns True
if at least one of the expressions is true. If both expressions are false, it returns False
. The or
operator is a key component in constructing compound logical conditions. It performs short-circuit evaluation, meaning that it stops evaluating as soon as it finds a true expression.
Python or
Keyword Examples
Here are some quick examples of how to use the or
keyword in Python:
>>> True or True
True
>>> True or False
True
>>> False or True
True
>>> False or False
False
>>> 5 > 3 or 2 < 4
True
>>> 5 > 3 or 2 > 4
True
>>> "Hi!" or []
'Hi!'
>>> "Hi!" or [1, 2, 3]
'Hi!'
>>> 0 or [1, 2, 3]
[1, 2, 3]
The first four examples show the truth table for the or
operator. Then, you have comparison expressions combined with or
. Their result is True
if at least one expression evaluates to True
, and False
if both are false.
In the last set of examples, you use or
to combine objects. In each expression, you get a specific object. Note that in these examples, you don’t get True
or False
.
Python or
Keyword Use Cases
Related Resources
Tutorial
Using the "or" Boolean Operator in Python
In this step-by-step tutorial, you'll learn how the Python "or" operator works and how to use it. You'll get to know its special features and see what kind of programming problems you can solve by using "or" in Python.
For additional information on related topics, take a look at the following resources:
- Python Booleans: Use Truth Values in Your Code (Tutorial)
- Using the Python or Operator (Course)
- Python Booleans: Leveraging the Values of Truth (Course)