A boolean in Python is a data type with only two possible values: True and False. These values are often the result of comparison or logical operations and are used to control the flow of programs.

is_python_fun = True
is_raining = False

print(type(is_python_fun))  # Output: <class 'bool'>
print(type(is_raining))     # Output: <class 'bool'>

The bool type in Python is a subclass of the integer type, which means True is equivalent to 1 and False is equivalent to 0.

print(True == 1)  # Output: True
print(False == 0)  # Output: True
print(True + True)  # Output: 2

Boolean Context: Truthy and Falsy Values

In Python, values are evaluated as either "truthy" or "falsy" in boolean contexts, such as conditional statements.

Falsy Values

The following values are considered falsy in Python:

  • None
  • False
  • 0 (any numeric type: 0, 0.0, 0j, etc.)
  • Empty sequences or collections: '', (), [], {}, set()
  • Objects of custom classes with __bool__() or __len__() returning False
print(bool(0))       # Output: False
print(bool(''))      # Output: False
print(bool([]))      # Output: False
print(bool(None))    # Output: False

Truthy Values

All values that are not falsy are truthy.

print(bool(42))       # Output: True
print(bool('Python')) # Output: True
print(bool([1, 2, 3])) # Output: True

Boolean Operations in Python

Python provides three logical operators to perform boolean operations:

1. and

The and operator returns True if both operands are truthy.

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

result = True and bool(2)
print(result)  # Output: True

2. or

The or operator returns True if at least one operand is truthy.

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

3. not

The not operator negates a boolean value.

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

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

Boolean Expressions and Comparison Operators

Comparison operators often produce boolean results and are frequently used in conditional expressions.

Comparison Operators

Operator Description Example
== Equal to 5 == 5True
!= Not equal to 5 != 4True
> Greater than 5 > 3True
< Less than 3 < 5True
>= Greater than or equal to 5 >= 5True
<= Less than or equal to 4 <= 5True
x = 10
y = 20

print(x < y)  # Output: True
print(x == y) # Output: False

Combining Comparisons

Python allows chaining comparison operators for cleaner expressions:

x = 10
print(5 < x < 15)  # Output: True

Using Booleans in Conditional Statements

Booleans are commonly used in conditional statements to control program flow.

age = 20

if age >= 18:
    print("You are an adult.")
else:
    print("You are a minor.")

Output:

You are an adult.

Practical Use Cases for Booleans

1. Default Arguments in Functions

Booleans are often used as default arguments for function parameters.

def greet(name: str, excited: bool = False) -> str:
    if excited:
        return f"Hello, {name}!!!"
    return f"Hello, {name}."

print(greet("Alice"))         # Output: Hello, Alice.
print(greet("Alice", True))   # Output: Hello, Alice!!!

2. Filtering Data

Booleans can be used to filter collections using filter():

from typing import List

numbers: List[int] = [0, 1, 2, 3, 4, 5]
filtered = list(filter(lambda x: x % 2 == 0, numbers))

print(filtered)  # Output: [0, 2, 4]

3. Assertions for Validation

Booleans are crucial for validating conditions using assert.

def divide(a: int, b: int) -> float:
    assert b != 0, "Division by zero is not allowed."
    return a / b

print(divide(10, 2))  # Output: 5.0
# print(divide(10, 0))  # Raises AssertionError

Common Pitfalls with Booleans

  1. Avoid Using is for Comparisons

    • Use == instead of is for comparing boolean values.
    print(True == 1)  # Output: True
    print(True is 1)  # Output: False
    
  2. Truthiness of Empty Objects

    • Be cautious with empty objects, as they evaluate to False even if not explicitly a boolean.
    print(bool([]))  # Output: False
    

Conclusion

Booleans in Python are more than just True and False. They form the foundation of control flow and logical operations, enabling powerful and expressive programming. By understanding how truthy and falsy values work, mastering boolean operations, and avoiding common pitfalls, you can write cleaner, more efficient Python code.

AUTHOR
PUBLISHED 28 January 2025
TOPICS