OR
What Is the OR Operator?
- The OR operator
orin Python is used to check if at least one of two conditions is true.
How to Use It:
The basic way to use the OR operator is:
pythonresult = condition1 or condition2condition1andcondition2are the conditions you want to compare.resultwill beTrueif at least one of the conditions is true.
Truth Table:
Here’s how the OR operator works with different conditions:
Operand1 Operand2 Return Value True True True True False True False True True False False False
Examples and Exercises:
Using OR with Boolean Values:
pythona = True b = True result = a or b print(a, 'or', b, 'is:', result) # Output: True or True is: True a = True b = False result = a or b print(a, 'or', b, 'is:', result) # Output: True or False is: True a = False b = True result = a or b print(a, 'or', b, 'is:', result) # Output: False or True is: True a = False b = False result = a or b print(a, 'or', b, 'is:', result) # Output: False or False is: FalseUsing OR with Non-Boolean Values:
- In Python, you can use numbers in place of boolean values (0 is False, any other number is True).
pythona = 5 b = -5 result = a or b print(a, 'or', b, 'is:', result) # Output: 5 or -5 is: 5 a = 4 b = 0 result = a or b print(a, 'or', b, 'is:', result) # Output: 4 or 0 is: 4 a = 0 b = 6 result = a or b print(a, 'or', b, 'is:', result) # Output: 0 or 6 is: 6 a = 0 b = 0 result = a or b print(a, 'or', b, 'is:', result) # Output: 0 or 0 is: 0
Summary:
- The OR operator
orin Python allows you to check if at least one of two conditions is true. It’s useful for making decisions in your code. Try the examples to see how it works!