Skip to main content

Command Palette

Search for a command to run...

Understanding Boolean Logic: The True and False of Programming - Part 1

Learning Boolean Logic: Distinguishing Between Real and Unreal Elements in Programming

Updated
7 min read
Understanding Boolean Logic: The True and False of Programming - Part 1

Boolean logic is an essential and foundational concept in the field of computer science and programming. It pertains to a specific data type that is capable of representing only two distinct values: true and false. This concept is named in honor of the renowned mathematician George Boole, who made significant contributions to the development of modern logic and algebra.

Boolean values play a pivotal role in making decisions and directing the flow of computer programs, as they allow for the evaluation and comparison of different conditions. They form the backbone of conditional statements, which are used to execute specific blocks of code based on whether a given condition is true or false. Furthermore, Boolean values are indispensable in performing logical operations, such as AND, OR, and NOT, which are essential for constructing complex logical expressions.

By determining the truth or falsity of various expressions, Booleans empower computers to process and respond to questions of logic. This capability is fundamental to a vast array of software applications and algorithms, ranging from simple decision-making tasks to more intricate problem-solving processes. For instance, Booleans are used in search engines to filter and refine search results, in control systems to regulate the behavior of machines, and in artificial intelligence algorithms to make decisions based on specific criteria.

Python has a concrete bool class that is used to represent Boolean Values. Boolean values can have one of two states: True or False, and they are used for making logical decisions in Python programs. However, the bool class is a subclass of the int class, i.e. they possess all the properties and methods of the integers, and some specialized ones such as and, or, etc.

>>> issubclass(bool,int)
True
>>> isinstance(True,bool)
True
>>> isinstance(True,int)
True
>>> isinstance(False,bool)
True
>>> isinstance(False,int)
True

The two constants are defined as True and False. These constants are singleton objects of type bool.

is vs ==

In the context of integers and specialized methods such as 'and', 'or', etc., the two fundamental constants are defined as True and False. These constants are unique, singleton objects of the bool data type, which is a subclass of the int data type. As a result, both True and False are instances of both bool and int.

Being singleton objects, True and False maintain the same memory address throughout the entire lifetime of an application. This characteristic allows for the comparison of any boolean expression to True and False using two distinct operators: the 'is' (identity) operator and the '==' (equality) operator. The 'is' operator checks if two variables refer to the same object in memory, while the '==' operator verifies if the values of two variables are equal. In the case of True and False, both operators can be used interchangeably for comparison purposes, as they will yield the same result due to the unique nature of these singleton objects.

>>> a == True
>>> a is True
# where a is a bool object

But since bool objects are also int objects, they can also be interpreted as the integers 1 and 0.

>>> int(True)
1
>>> int(False)
0

But True and 1 are not the same object as well as False and 0 are not same objects.

>>> id(True)
140703300049000
>>> id(False)
140703300049032
>>> id(1)
3162094987568
>>> id(0)
3162094987536
>>> True is 1
False
>>> True == 1
True
>>> False is 0
False
>>> False == 0
True

Boolean Constructor

In Python, the bool() constructor is used to create Boolean objects. However, it's important to note that the bool() constructor primarily converts other values into Boolean values (True or False) rather than directly creating Boolean objects.

When we use bool() with other data types, it converts them to their corresponding Boolean values. In general, the following rules apply: - Numeric values: 0 is converted to False, and any other numeric value is converted to True. - Sequences (e.g., lists, tuples, strings): An empty sequence is converted to False, and a non-empty sequence is converted to True. - None is always converted to False. - Custom objects: If we define a custom class, we can control how instances of that class are converted to Boolean values by implementing the __bool__() or __len__() special methods.

Here are some examples:

bool_value = bool(0)          # bool_value is False
bool_value = bool(42)         # bool_value is True
bool_value = bool([])         # bool_value is False (empty list)
bool_value = bool([1, 2, 3])  # bool_value is True (non-empty list)

we can also use bool() to create Boolean objects explicitly, but this is less common because we typically work directly with the True and False keywords for Boolean values.

bool_object = bool(True)      # bool_object is True
bool_object = bool(False)     # bool_object is False

Object Truth Values

In Python, every object has an associated truth value that determines whether it evaluates to True or False in a Boolean context. Understanding how objects are evaluated for truthiness is essential when working with conditions, loops, and logical expressions.

Here are the general rules for object truth values in Python:

  1. Falsy Values:

    • Objects that are considered "falsy" evaluate to False in a Boolean context. Common examples of falsy values include:

      • False itself

      • Numeric zero values: 0, 0.0, 0j (complex zero)

      • Empty sequences and collections: "" (empty string), [] (empty list), () (empty tuple), {} (empty dictionary), and set() (empty set)

      • None: The absence of a value is considered falsy.

  2. Truthy Values:

    • Objects that are considered "truthy" evaluate to True in a Boolean context. Generally, any object not explicitly listed as falsy is considered truthy. Common examples of truthy values include:

      • True

      • Non-zero numeric values

      • Non-empty sequences and collections

      • Non-empty strings

      • Non-empty user-defined objects (if the object's __bool__() or __len__() method returns True or a non-zero value)

Here are some examples of object truth values in Python:

# Falsy values
bool(False)        # False
bool(0)            # False
bool("")           # False
bool([])           # False
bool(None)         # False

# Truthy values
bool(True)         # True
bool(42)           # True (non-zero integer)
bool("Hello")      # True (non-empty string)
bool([1, 2, 3])    # True (non-empty list)

Keep in mind that these rules for truthiness and falsiness are fundamental to Python's behavior in conditional statements (if, elif, else), loop control (while, for), and logical expressions (and, or, not). They allow you to write code that makes decisions based on the truth values of objects.

under the hood

In Python, __bool__() is a special method (sometimes called "magic method" or "dunder method") that you can define in your custom classes to control how instances of your class are evaluated in a Boolean context. This method should return either True or False to indicate whether an object of your class should be considered truthy or falsy, respectively.

The __bool__() method is called automatically when an instance of your class is used in a Boolean context, such as in an if statement or when using logical operators like and, or, or not. By defining this method, you can customize the truth value of your objects based on their internal state or logic.

>>> def __bool__(self):
    return self != 0

>>> bool(100)
True
>>> bool(0)
False

when we call bool(100) Python executes 100.__bool__() and therefore returns the result of 100 != 0 which is True.

When we call bool(0) Python executes 0.__bool__() and therefore returns the result of 0 != 0 which is False.

Here's an example of how you might define __bool__() in a custom class:

class MyClass:
    def __init__(self, value):
        self.value = value

    def __bool__(self):
        # Define custom logic for truthiness
        return self.value > 0

# Create instances of MyClass
obj1 = MyClass(5)
obj2 = MyClass(0)

# Using instances in Boolean context
if obj1:
    print("obj1 is truthy")  # This will be printed because obj1's __bool__() returns True
else:
    print("obj1 is falsy")

if obj2:
    print("obj2 is truthy")
else:
    print("obj2 is falsy")  # This will be printed because obj2's __bool__() returns False

In the example above, the __bool__() method has been defined to return True when the value attribute of MyClass is greater than 0 and False otherwise. As a result, instances of MyClass will behave as truthy or falsy based on this custom logic.

Keep in mind that if you don't define __bool__() in your class, Python will use a default implementation that returns True for all instances of your class, making them truthy. Defining __bool__() allows you to control the truth value more precisely according to your class's semantics.

In conclusion, Boolean logic is a fundamental concept in computer science and programming, enabling computers to make decisions and process logical questions. Python's bool class represents Boolean values, which are used in conditional statements, loops, and logical expressions. Understanding object truth values and the __bool__() method helps developers create more efficient and precise code, tailoring their programs to specific needs.

F

Semma..bro..

Python

Part 16 of 30

The Python Learning Series is a comprehensive and structured approach to mastering the Python programming. It is designed to cater to learners of all levels,from beginners to experienced.

Up next

Understanding Boolean Logic: The True and False of Programming - Part 2

Learning Boolean Logic: Distinguishing Between Real and Unreal Elements in Programming