Booleans are the simplest data type in Python. A boolean can hold only one of two possible values: True or False. Think of them as the logical switches of your code, like an on/off switch, used to represent the truth value of an expression.
Unlike many other programming languages that use lowercase true or false, Python is very strict about capitalization.
- Correct:
is_active = True - Incorrect:
is_active = true(This will cause aNameError)
Booleans as Integers
While representing Booleans as True or False will work in all python application, it is worth knowing that Booleans are subclass of integers. Under the hood, Python treats:
- True as the value 1
- False as the value 0
Let's look at the code block below to prove that booleans are, in fact, integers:
If you run the code above it will return True for both, proving that Booleans inherit all the properties of integers. This shared DNA means that wherever an integer is expected, a Boolean can usually step in.
Mathematical Operations on Booleans
Since python maps True to 1, and False to 0, you can perform standard arithmetic operations on them. Lets see some examples.
Logical Operators: and, or, not
In addition to math, Booleans are primarily used with Logical Operators. These allow you to combine or invert truth values to build complex logic.
- and: Returns True only if both sides are True.
- or: Returns True if at least one side is True.
- not: Inverts the value (True becomes False, and vice-versa).
The bool() Function: Truthy and Falsy
Every object in Python has an inherent "truthiness." You can check whether any value is considered True or False by passing it into the bool() function.
In Python, almost everything is considered Truthy except for a very specific list of Falsy values:
- The number 0 (or 0.0)
- Empty sequences like "" (strings), [] (lists), or () (tuples).
- The value None.
- The Boolean False itself.
Truthy and Falsy values
"Truthy" and "Falsy" are terms used to describe how non-boolean values (like strings, numbers, or lists) behave when they are evaluated in a logical context.
- Truthy: A value is "Truthy" if it resolves to True when passed into a boolean check. For example, any non-zero number or a string with text in it is considered Truthy.
- Falsy: A value is "Falsy" if it resolves to False. This usually represents "emptiness" or "nothingness," such as the number 0, an empty string "", or the value None.
Summary
- Fixed Values: Booleans only have two values: True and False.
- Strict Case: They must be capitalized; lowercase true or false will throw an error.
- Integer Roots: Under the hood, True is 1 and False is 0.
- Truthiness: Use bool() to determine if a value is "Truthy" or "Falsy."
