Sobes.tech
Junior

How do the logical operators and, or, and not work in Python?

sobes.tech AI

Answer from AI

Operators and, or, and not are used to combine or modify logical expressions.

  • and: Returns True if both operands are true. Otherwise, returns False. In short-circuit evaluation, if the left operand is false, the right is not evaluated.

    # Example of and
    print(True and True)    # True, both are True
    print(True and False)   # False, one is False
    print(False and True)   # False, one is False
    print(False and False)  # False, both are False
    
  • or: Returns True if at least one operand is true. Returns False only if both operands are false. In short-circuit evaluation, if the left operand is true, the right is not evaluated.

    # Example of or
    print(True or True)    # True, both are True
    print(True or False)   # True, one is True
    print(False or True)   # True, one is True
    print(False or False)  # False, both are False
    
  • not: Negates the logical value of the operand. Returns True if the operand is false, and False if the operand is true.

    # Example of not
    print(not True)   # False
    print(not False)  # True
    

Besides boolean values (True and False), these operators also work with other data types, using their "truthiness" or "falsiness" in a boolean context:

  • Numbers: nonzero (true), zero (false).
  • Strings, lists, tuples, dictionaries, sets: non-empty (true), empty (false).
  • None: false.

When evaluating and and or, Python returns not only True or False, but also one of the operands (short-circuiting):

  • a and b: If a is false, returns a. Otherwise, returns b.
    print(0 and 5)  # 0 (0 is false)
    print(5 and 0)  # 0 (5 is true, returns 0)
    print(1 and 2)  # 2 (1 is true, returns 2)
    
  • a or b: If a is true, returns a. Otherwise, returns b.
    print(0 or 5)  # 5 (0 is false, returns 5)
    print(5 or 0)  # 5 (5 is true, returns 5)
    print(1 or 2)  # 1 (1 is true, returns 1)
    

This behavior is important for conditional expressions and setting default values.