Boolean Data Type (bool)
In Python, the bool
data type represents binary values, specifically True or False. Booleans are fundamental for decision-making, conditional statements, and controlling the flow of your program. In this section, we'll explore the bool
type and its practical use.
1. Creating Boolean Variables
You can create boolean variables by using the keywords True
and False
. These represent the two possible boolean values:
is_positive = True
is_negative = False
Booleans are typically used to represent conditions, such as whether a condition is met (True) or not met (False).
2. Comparison Operators
Boolean variables are often created by using comparison operators, which compare two values and return a boolean result. Common comparison operators include:
-
==
(equal to) -
!=
(not equal to) -
<
(less than) -
>
(greater than) -
<=
(less than or equal to) -
>=
(greater than or equal to)
For example:
x = 5
y = 10
result = x < y # True (5 is less than 10)
3. Logical Operators
Logical operators are used to combine boolean values or expressions. Python provides three main logical operators: and
, or
, and not
.
-
and
: Returns True if both operands are True. -
or
: Returns True if at least one operand is True. -
not
: Returns the opposite of the operand's value.
For example:
x = True
y = False
result1 = x and y # False (both are not True)
result2 = x or y # True (at least one is True)
result3 = not x # False (opposite of True is False)
4. Boolean Expressions
Boolean expressions are conditions that evaluate to a boolean value. They are used in decision-making structures, such as if
statements:
x = 5
y = 10
if x < y:
print("x is less than y")
else:
print("x is not less than y")
The condition x < y
evaluates to True, so the code block under the if
statement is executed.
5. Truthiness and Falsiness
In Python, various non-boolean values can be evaluated as True or False in a boolean context. Some general rules include:
- False, None, 0, and empty sequences (e.g., empty strings, lists, or dictionaries) are considered False.
- All other values are considered True.
x = 0
y = "Hello"
if x:
print("x is True")
else:
print("x is False") # Output: "x is False"
if y:
print("y is True") # Output: "y is True"
else:
print("y is False")
Understanding boolean values and expressions is essential for writing conditional logic and controlling the flow of your Python programs. In the following sections, we'll explore how to use boolean variables in various contexts and conditional statements.