Logical operators in Python

 


Logical operators in Python are used to combine conditional statements or evaluate multiple conditions. These operators return a boolean value (True or False).

Logical Operators:

  • and – Returns True if both conditions are True.

    x = 5

  • y = 10

  • print(x > 3 and y < 15)  # Output: True


  • or – Returns True if at least one condition is True.

    x = 5

  • y = 10

  • print(x > 10 or y < 15)  # Output: True


  • not – Reverses the logical state of the operand. If the condition is True, it returns False, and vice versa.

    x = 5

  • print(not x > 10)  # Output: True (because x > 10 is False, and `not` reverses it)


Examples:

Example 1: Using and operator

  • a = 10

  • b = 5

  • c = 7


  • # Both conditions need to be True for the result to be True

  • result = (a > b) and (c < a)

  • print(result)  # Output: True (10 > 5 is True and 7 < 10 is True)


Example 2: Using or operator

  • x = 3

  • y = 8


  • # Only one condition needs to be True for the result to be True

  • result = (x > 5) or (y > 5)

  • print(result)  # Output: True (y > 5 is True)


Example 3: Using not operator

  • x = 7


  • # Reverses the condition's boolean value

  • result = not (x < 5)

  • print(result)  # Output: True (x < 5 is False, so `not` makes it True)


Example 4: Combining multiple logical operators

  • x = 10

  • y = 20

  • z = 5


  • # Combining and, or, and not operators

  • result = (x < y) and (not z > 10)

  • print(result)  # Output: True (x < y is True and z > 10 is False, so `not` makes it True)


Truth Tables for Logical Operators:

  • and operator:

Condition 1

Condition 2

Result

True

True

True

True

False

False

False

True

False

False

False

False


  • or operator:

Condition 1

Condition 2

Result

True

True

True

True

False

True

False

True

True

False

False

False


  • not operator:

Condition

Result

True

False

False

True

Key Points:

  • Logical operators are often used in conditional statements to check multiple conditions.

  • The and operator returns True only when both conditions are True.

  • The or operator returns True if at least one condition is True.

  • The not operator inverts the boolean value of a condition.

Let me know if you need more examples or clarification! 😊


Post a Comment

0 Comments