Booleans

Booleans in Python

Python's Boolean data type has two values: True or False. These use capital letters, unlike lowercase letters in JavaScript. These are used to represent the truth value of expressions and are integral to control flow in Python programs. You can evaluate expressions to return Boolean values such as:

print(10 > 5)  # Output: True
print(10 == 5) # Output: False

Additionally, you can use the bool() function to determine the truth value of an object:

print(bool(0))        # Output: False
print(bool(1))        # Output: True
print(bool(""))       # Output: False
print(bool("Python")) # Output: True

In Python, values like 0, None, '', [], and {} are considered False, while most other values are considered True.

Boolean Operators

Python provides three primary Boolean operators: and, or, and not.

And returns True if both operands are True.

print(True and True)   # Output: True
print(True and False)  # Output: False

The and operator returns the first falsy value or the last value if all are truthy.

print(0 and 5)   # Output: 0
print(5 and 0)   # Output: 0
print(5 and 10)  # Output: 10

or returns True if at least one operand is True.

print(True or False)  # Output: True
print(False or False) # Output: False

Similar to and, the or operator returns the first truthy value or the last value if all are falsy.

print(0 or 5)   # Output: 5
print(5 or 0)   # Output: 5
print(0 or None)  # Output: None

not returns the opposite Boolean value of the operand. The not operator always returns a Boolean value, inverting the truthiness of its operand.

print(not True)  # Output: False
print(not False) # Output: True

Identity Operators

Python's identity operators check whether two variables reference the same object in memory:

  • is: Returns True if both variables point to the same object.
  • is not: Returns True if variables point to different objects.
#  Here, a and b reference the same list object, while c is a separate object with the same content.
a = [1, 2, 3]
b = a
c = [1, 2, 3]
print(a is b)   # Output: True
print(a is c)   # Output: False
print(a == c)   # Output: True

True and False are singletons in Python, meaning there's only one instance of each in a Python program. Therefore, using is with Boolean values is valid.

x = True
print(x is True)  # Output: True

However, for general truth value testing, it's recommended to use == or simply rely on the truthiness of the value.

if x:
    print("x is truthy")

Membership Operators

Membership operators check for membership within sequences like lists, tuples, strings, etc.:

  • in: Returns True if the specified value is present.
  • not in: Returns True if the specified value is absent.
fruits = ['apple', 'banana', 'cherry']
print('banana' in fruits)     # Output: True
print('orange' not in fruits) # Output: True