Python has a built-in data type called “bool” that represents boolean values. A boolean value can have one of two possible states: True or False (both capitalized).
For example:
done = False
done = True
Booleans are particularly useful when working with conditional control structures like if statements. They allow you to perform different actions based on the truthiness or falsiness of a condition.
Here’s an example:
done = True
if done:
# run some code here
else:
# run some other code
When evaluating a value to determine if it’s True or False, Python has specific rules based on the type of value being checked:
- Numbers are always considered True, except for the number 0.
- Strings are considered False only when they are empty.
- Lists, tuples, sets, and dictionaries are considered False only when they are empty.
To check if a value is a boolean, you can use the following methods:
Method 1:
done = True
type(done) == bool # True
Method 2:
done = True
isinstance(done, bool) # True
Additionally, Python provides two useful global functions for working with booleans:
- The
any()
function returns True if any of the values in an iterable (e.g., a list) are True.
Example:
book_1_read = True
book_2_read = False
read_any_book = any([book_1_read, book_2_read])
- The
all()
function returns True if all of the values passed to it are True.
Example:
ingredients_purchased = True
meal_cooked = False
ready_to_serve = all([ingredients_purchased, meal_cooked])
By understanding and utilizing boolean values in Python, you can effectively control the flow of your program and make decisions based on logical conditions.