Logical Operators in Python

Python’s logical operators are used to combine conditional statements. There are three types of logical operators: and, or, and not. In this tutorial, we will explore how to use these operators in Python.

The and Operator

The and operator returns True if both the conditions are true. If either condition is false, it returns False.

x = 5
y = 10
if x > 2 and y < 15:
    print("Both conditions are met")

The or Operator

The or operator returns True if at least one of the conditions is true. If both conditions are false, it returns False.

x = 5
y = 10
if x > 2 or y < 5:
    print("At least one condition is met")

The not Operator

The not operator returns the opposite of the condition. If the condition is true, it returns False, and if the condition is false, it returns True.

x = 5
if not x > 10:
    print("The condition is not met")

Short-Circuit Evaluation

Python’s logical operators use short-circuit evaluation. This means that if the first condition in an and statement is false, the second condition will not be evaluated. Similarly, if the first condition in an or statement is true, the second condition will not be evaluated.

def print_and_return(value):
    print(value)
    return value

res = print_and_return(False) and print_and_return(True)
# Only "False" will be printed

Customizing Behavior for Custom Classes

In Python, you can customize how your classes behave with logical operators by implementing the __bool__ method.

class Test:
    def __init__(self, value):
        self.value = value

    def __bool__(self):
        print("__bool__ called")
        return bool(self.value)

test = Test(True)
if test and True:
    print("Condition is met")
# "__bool__ called" will be printed

Using Logical Operators with NumPy Arrays

When working with NumPy arrays, you can use the np.logical_and and np.logical_or functions to perform element-wise logical operations.

import numpy as np

arr1 = np.array([True, False, True])
arr2 = np.array([False, True, True])

result = np.logical_and(arr1, arr2)
print(result)  # [False, False, True]

In summary, Python’s logical operators are used to combine conditional statements. The and, or, and not operators can be used to create complex conditions, and the short-circuit evaluation feature can improve performance. By implementing the __bool__ method in custom classes, you can customize how they behave with logical operators.

Leave a Reply

Your email address will not be published. Required fields are marked *