AND

What Is the AND Operator?

  • The AND operator and in Python is used to check if both conditions in a statement are true.

How to Use It:

  • The basic way to use the AND operator is:

    python
    result = condition1 and condition2
    
    • condition1 and condition2 are the conditions you want to compare.
    • result will be True only if both conditions are true.

Truth Table:

  • Here’s how the AND operator works with different conditions:

     
    Operand1  Operand2  Return Value
    True      True      True
    True      False     False
    False     True      False
    False     False     False
    

Examples and Exercises:

  1. Using AND with Boolean Values:

    python
    a = True
    b = True
    result = a and b
    print(a, 'and', b, 'is:', result)  # Output: True and True is: True
    
    a = True
    b = False
    result = a and b
    print(a, 'and', b, 'is:', result)  # Output: True and False is: False
    
    a = False
    b = True
    result = a and b
    print(a, 'and', b, 'is:', result)  # Output: False and True is: False
    
    a = False
    b = False
    result = a and b
    print(a, 'and', b, 'is:', result)  # Output: False and False is: False
    
  2. Using AND 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 = 3
    result = a and b
    print(a, 'and', b, 'is:', result)  # Output: 5 and 3 is: 3
    
    a = 8
    b = 0
    result = a and b
    print(a, 'and', b, 'is:', result)  # Output: 8 and 0 is: 0
    
    a = 0
    b = -8
    result = a and b
    print(a, 'and', b, 'is:', result)  # Output: 0 and -8 is: 0
    
    a = 0
    b = 0
    result = a and b
    print(a, 'and', b, 'is:', result)  # Output: 0 and 0 is: 0
    

Summary:

  • The AND operator and in Python allows you to check if two conditions are both true. It’s useful for making decisions in your code. Try the examples to see how it works!