Python or keyword is used as a logical operator to perform in performing compound boolean expressions. It returns True if at least one of the expressions is True.
The or keyword is a logical operator used to combine multiple conditions in a conditional statement.
It returns True if any of the conditions evaluate to True.
Its behaviour can be summarized using the following truth table:
result = False or False print(result) result = False or True print(result) result = True or False print(result) result = True or True print(result)
Output:
False True True True
As seen from the truth table, the or keyword evaluates to True as long as at least one of the conditions is True.
Now, let’s look at a few examples.
Simplifying Conditional Statements
One of the primary use cases of the or keyword is simplifying conditional statements.
Instead of writing multiple if-else statements, the or keyword allows us to express complex conditions in a concise manner.
Let’s consider an example:
name = input("What is your name? ") if name == "Ann" or name == "Mary": print("Welcome, Ann or Mary!") else: print("Hello, stranger!")
In the above example, the program checks if the inputted name is either “Ann” or “Mary” using the or keyword.
If the condition is True, it displays a personalized welcome message.
By using the or keyword, we reduce the number of if statements and make the code more readable.
Default Values and Assignments
The or keyword is also useful when dealing with default values and variable assignments.
Consider the following example:
def get_user_name(username): name = username or "Guest" print(f"Welcome, {name}!") get_user_name("John") get_user_name("")
Output:
Welcome, John! Welcome, Guest!
In the above code, the or keyword is used to assign a default value of “Guest” to the variable name if the username argument is an empty string.
This ensures that the program does not throw an error or display an undesired output.
Checking for the Presence of Elements
The or keyword can also be used to check if a particular element exists within a sequence, such as a list or a string.
Consider the following example:
fruits = ["apple", "banana", "orange"] if "apple" in fruits or "pear" in fruits: print("You have apples or pears!") else: print("You don't have apples or pears!")
Output:
In this case, the or keyword is used to check if either “apple” or “pear” exists in the fruits list.
If at least one of the conditions is True, it prints an appropriate message.
Conclusion
The or keyword in Python is a valuable tool for simplifying conditional statements, setting default values, and checking for the presence of elements.