Python OR Keyword
Python OR is a logical operator keyword. The OR operator returns True if at least one of the operands becomes to be True.
Note:
- In Python "or" operator does not return True or False.
- The "or" operator in Python returns the first operand if it is True else the second operand.
Let’s start with a simple example to understand how "or" works in a condition.
age = 16
p = False
if age >= 18 or p:
print("Access granted")
else:
print("Access denied")
Output
Access denied
Explanation: The if condition is not being evaluated as True because neither of the conditions (age >= 18 or p) are True.
Python OR Keyword Truth Table
| Input 1 | Input2 | Output |
|---|---|---|
| True | True | True |
| True | False | True |
| False | True | True |
| False | False | False |
Let's explore some of the use cases of "or" keyword with examples.
Use of "or" in Conditional Statements
In the if statement python uses the "or" operator to connect multiple conditions in one expression.
a = 55
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
Output
a is greater than b
Use of "or" in Loops
"or" operator can be used inside loops to control execution based on multiple conditions.
Example :
# break the loop as soon it sees 'k'
# or 'f'
i = 0
s = 'geeksforgeeks'
while i < len(s):
if s[i] == 'k' or s[i] == 'f':
i += 1
break
print(s[i])
i += 1
Output
g e e
Using "or" for Default Values
"or" keyword is often used to set default values when dealing with empty or None variables.
user = ""
cur_user = user or "Guest"
print(cur_user) # when user is empty
user = "geeks"
cur_user = user or "Guest" # when user in not empty
print(cur_user)
Output
Guest geeks
Explanation:
- when user is an empty string ("") (which is falsy), "or" selects "Guest".
- when user contains a value (which is truthy), it gets assigned to cur_user because "or".