The or keyword is a logical operator used to combine two or more conditions. It returns True if at least one of the conditions is True. It is commonly used in if statements to check multiple conditions together.
age = 16
permission = False
if age >= 18 or permission:
print("Access granted")
else:
print("Access denied")
Output
Access denied
Explanation: The value of age is 16, so the condition age >= 18 is False. The variable permission is also False. Since both conditions are False, the or expression evaluates to False, and the else block is executed.
Syntax
The general syntax of the or keyword is shown below:
condition1 or condition2
Or, it can be used inside an if statement as follows:
if condition1 or condition2:
# code
Truth Table
The following truth table shows the result of the or keyword for different combinations of Boolean values:
| First Condition | Second Condition | Result |
|---|---|---|
| True | True | True |
| True | False | True |
| False | True | True |
| False | False | False |
Explanation: The or keyword returns True if at least one of the conditions is True. It returns False only when both conditions are False.
In Conditional Statements
The or keyword is commonly used in if statements when any one of multiple conditions can satisfy the condition.
marks = 45
res = True
if marks >= 50 or res:
print("Pass")
else:
print("Fail")
Output
Pass
Explanation: The value of marks is less than 50, but res is True. Since at least one condition is True, the print() statement is executed.
In Loops
The or keyword can be used in loops to continue or stop execution based on multiple conditions.
i = 1
while i <= 5:
if i == 3 or i == 5:
print(i)
i += 1
Output
3 5
Explanation: The condition i == 3 or i == 5 becomes True when the value of i is either 3 or 5. Therefore, only these values are printed.
With Default Values
The or keyword is often used to assign a default value when a variable is empty or None.
user = ""
current_user = user or "Guest"
print(current_user)
user = "Rocky"
current_user = user or "Guest"
print(current_user)
Output
Guest Rocky
Explanation:
- When user is an empty string (""), it is treated as a falsy value, so "Guest" is assigned to current_user.
- When user contains "Rocky", it is a truthy value, so current_user is assigned the value of user.