Python Booleans
By Flavio Copes
Learn how Python booleans work, with the True and False values, how other types evaluate as truthy or falsy, and the handy any() and all() global functions.
Python provides the bool type, which can have two values: True and False (capitalized)
done = False
done = True
Booleans are especially useful with conditional control structures like if statements:
done = True
if done:
# run some code here
else:
# run some other code
Notice we write if done:, not if done == True:. The comparison is redundant, since done already holds a boolean.
Truthy and falsy values
When evaluating a value for True or False, if the value is not a bool we have some rules depending on the type we’re checking:
- numbers are always
Trueexcept for0(and0.0) - strings are
Falseonly when empty - lists, tuples, sets, dictionaries are
Falseonly when empty
You can check how any value evaluates by passing it to the bool() function:
bool(0) # False
bool(3.14) # True
bool('') # False
bool('hello') # True
bool([]) # False
This matters in conditionals. Writing if items: runs the code only when the items list has at least one element.
Checking if a value is a boolean
You can check if a value is a boolean in this way:
done = True
type(done) == bool # True
Or using isinstance(), passing 2 arguments: the variable, and the bool class:
done = True
isinstance(done, bool) # True
Booleans are numbers, too
In Python, bool is a subclass of int. True behaves as 1 and False as 0:
True + True # 2
True * 8 # 8
This has a practical use: sum() counts how many values in a list are True:
answers = [True, False, True, True]
sum(answers) # 3
But it also hides a pitfall: isinstance(True, int) returns True. If you’re inspecting types and need to tell integers and booleans apart, check for bool first, before checking for int.
The any() and all() functions
The global any() function is also very useful when working with booleans, as it returns True if any of the values of the iterable (a list, for example) passed as argument are True:
book_1_read = True
book_2_read = False
read_any_book = any([book_1_read, book_2_read])
The global all() function is similar, but returns True only if all of the values passed to it are True:
ingredients_purchased = True
meal_cooked = False
ready_to_serve = all([ingredients_purchased, meal_cooked])
Here ready_to_serve is False, because meal_cooked is False.
Related posts about python: