True means "yes" and false means "no." In Python we rarely need to use the "bool
" built-in. Often expressions can just be used directly as bool
expressions.
In a class
, we can provide a "bool
" method that returns True or False. This method indicates how an instance of the class
evaluates when used with "bool."
Here, we use the bool
built-in with some expressions and constants. We see how Python evaluates the truth of things. A nonempty string
is True, but None
is False.
bool
" keyword and we would still have the same results.# Compute bools based on expressions and constants. value1 = bool(2 == 3) print(value1) value2 = bool(None) print(value2) value3 = bool("cat") print(value3) print() # Compute bools based on these variables. a = 10 b = 10 value4 = bool(a == b) print(value4) value5 = bool(a != b) print(value5) value6 = bool(a > b) print(value6)False False True True False False
Class
, def bool
Let us continue with a class
. We implement the "__bool__" method. This method must return True or False (this is the bool
value a class
instance evaluates to).
class
evaluates to True only if the "value" field is equal to 1. All other values will result in False.class Box: def __init__(self, value): # Initialize our box. self.value = value def __bool__(self): # This returns true only if value is 1. if self.value == 1: return True else: return False # Create Box instances. # ... Use bool on them. box = Box(0) result = bool(box) print(result) box = Box(1) result = bool(box) print(result) box = Box(2) result = bool(box) print(result)False True False
Often we can omit the "bool
" keyword entirely—this can lead to clearer, shorter code. Here we store a bool
in the correct and correct_bool
variables.
bool
here is probably best left out.value = 5 # Both of these expressions evaluate to a bool. # ... The bool keyword is not required. correct = value == 5 correct_bool = bool(value == 5) # Print results. print(correct) print(correct_bool)True True
Let us be thorough with our examination of bool
. When called with no arguments, bool()
returns False. I have never used this in a Python program.
# These evaluate to false. print(bool()) print(bool(None)) # The inner bool returns value. print(bool(bool())) # A string evaluates to true. print(bool("a"))False False False True
int
A bool
might look like a separate type. But it really is just an int
—a subclass of an int
. A bool
can be only True or False.
Using bool()
has been, in my experience, rare in simple Python programs. But it is important to know about it, for when it is needed.