Logical Operators

  • Python logical operators (and, or, not) are keywords used to evaluate multiple conditions and return a Boolean result (True or False). These operators help control the flow of your program by allowing multiple conditions to be combined in if, elif, or while statements.
  • Logical operators in Python are used to combine multiple conditions or invert a condition. They return Boolean values: True or False.

    Python provides three logical operators:

    Operator

    Description

    Example

    and

    Returns True if both conditions are True

    (5 > 3) and (2 < 4) → True

    or

    Returns True if at least one condition is True

    (5 > 3) or (2 > 4) → True

    not

    Reverses the Boolean value

    not(True) → False

    Logical operators are commonly used in decision-making, loops, and complex conditions.

    Logical Operators – Truth Table

    1. AND Operator (and)

    Returns True only if both conditions are True.

    A

    B

    A and B

    True

    True

    True

    True

    False

    False

    False

    True

    False

    False

    False

    False

    2. OR Operator (or)

    Returns True if at least one condition is True.

    A

    B

    A or B

    True

    True

    True

    True

    False

    True

    False

    True

    True

    False

    False

    False

    3. NOT Operator (not)

    Reverses the Boolean value.

    A

    not A

    True

    False

    False

    True

Logical Operators Example

Demonstrates the use of and, or, and not operators with two conditions.

# Python program to demonstrate logical operators
a = 10
b = 5
c = 8
# Using 'and' operator
print("(a > b) and (b < c):", (a > b) and (b < c))  # True because both conditions are True

# Using 'or' operator
print("(a < b) or (b < c):", (a < b) or (b < c))    # True because one condition is True

# Using 'not' operator
print("not(a > b):", not(a > b))                   # False because a > b is True, 'not' reverses it