OR

What Is the OR Operator?

  • The OR operator or in 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:

    python
    result = condition1 or condition2
    
    • condition1 and condition2 are the conditions you want to compare.
    • result will be True if 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:

  1. Using OR with Boolean Values:

    python
    a = 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: False
    
  2. Using OR with Non-Boolean Values:

    • In Python, you can use numbers in place of boolean values (0 is False, any other number is True).
    python
    a = 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 or in 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!