In Python, bool (short for Boolean) is a built-in data type used to represent truth values: True and False. Booleans are essential in control flow, comparisons, and logical operations.
1. What is a Boolean?
Booleans are one of the simplest types in Python. There are only two Boolean values:
True False
These values are case-sensitive, so true and false (lowercase) will raise an error.
print(True) # Correct print(false) # NameError: name 'false' is not defined
2. Boolean Type and type() Function
You can use the type() function to check the type of a Boolean value:
print(type(True)) # <class 'bool'> print(type(False)) # <class 'bool'>
3. Boolean Values from Expressions
Boolean values are commonly the result of comparison or logical expressions:
print(5 > 3) # True print(2 == 2) # True print(4 <= 1) # False
Each comparison returns a Boolean.
4. Boolean Values of Different Data Types
In Python, you can use the bool() constructor to convert other data types into Boolean values.
Rules:
- Falsy Values (evaluated as
False):NoneFalse0,0.0""(empty string)[],{},(),set()(empty collections)
- Truthy Values (evaluated as
True):- Non-zero numbers
- Non-empty strings
- Non-empty containers
Examples:
print(bool(0)) # False
print(bool(42)) # True
print(bool("")) # False
print(bool("Hello")) # True
print(bool([])) # False
print(bool([1, 2])) # True
5. Boolean Operators
Python includes three primary logical operators:
| Operator | Description | Example |
| and | True if both conditions are True | True and False → False |
| or | True if at least one is True | True or False → True |
| not | Inverts the value (True → False, False → True) | not True → False |
Examples:
a = True b = False print(a and b) # False print(a or b) # True print(not a) # False
6. Booleans in Control Flow
Booleans are crucial for control structures like if, while, etc.
if statement:
x = 10
if x > 5:
print("x is greater than 5")
else:
print("x is 5 or less")
while loop:
count = 0
while count < 3:
print("Counting:", count)
count += 1
7. Identity of Boolean Values
In Python, True and False are instances of the bool class, which is a subclass of int.
print(isinstance(True, int)) # True print(True == 1) # True print(False == 0) # True
This also means:
print(True + True) # 2 print(False + True) # 1
