Python Boolean Values¶
In Python, Boolean values represent one of two states: True or False.
We frequently evaluate expressions to yield a Boolean value. This typically happens when using comparison operators, membership operators, or when generally evaluating the "truthiness" of data.
# Evaluating comparison operators
print(10 > 9) # Returns True
print(10 == 9) # Returns False
print(10 < 9) # Returns False
Using Booleans in Conditions¶
Comparison operators returning Booleans are the foundation of conditional logic, such as if statements:
The bool() Function¶
You can use the built-in bool() function to evaluate any object or value. It will return either True or False based on Python's rules for "truthiness" and "falsiness."
Truthy Values (Most Values are True)¶
Almost any value is evaluated to True if it contains some sort of content.
- Strings: Any string is
True, except for empty strings. - Numbers: Any number is
True, except0. - Collections: Any list, tuple, set, or dictionary is
True, except for empty ones.
Falsy Values¶
There are very few values that evaluate to False. They generally represent "empty" or "null" concepts:
- The boolean
False - The
Noneobject - The number
0 - Empty sequences and collections:
"",(),[],{}
Objects with Custom Lengths¶
Another scenario where an object evaluates to False is if you are dealing with a custom class that has a __len__() method configured to return 0 or False.
Booleans as Return Values¶
Functions can be designed to return Boolean values, which is highly useful for writing clean, readable conditions.
Here is a practical example of using a Boolean-returning function directly within a conditional statement:
Note: Python also has several built-in functions that return Boolean values. A common example is the
isinstance()function, which checks if an object is instance of a class or not.