Sub topic 1
The bool type: True and False
Prerequisites
This chapter assumes you can write basic Python: variables, functions, and if statements. You should also know the built-in types int, str, list, and dict. Later chapters cover truthiness, comparisons, and None in detail. This one introduces the type that underlies all of them.
What bool is
bool is the built-in type for truth values. It has exactly two instances, True and False. Both are singletons: the interpreter creates each once, and every use refers to that same object. True and False are keywords, so you cannot reassign them. They are capitalized, and true or false raises a NameError.
print(type(True)) # <class 'bool'>
print(type(False)) # <class 'bool'>
print(True is True) # TrueYou rarely write True or False directly. Most booleans come from comparisons such as x > 3, membership tests such as "a" in text, and methods such as str.isdigit().
bool is a subclass of int
bool inherits from int. True behaves as the integer 1 and False as the integer 0, so you can use them in arithmetic.
print(isinstance(True, int)) # True
print(True + True) # 2
print(False * 10) # 0
print(True == 1) # TrueThis is useful for counting. Summing booleans counts how many are true:
scores = [55, 80, 92, 40, 71]
passed = sum(score >= 60 for score in scores)
print(passed) # 3The arithmetic result is an int, not a bool. True + True is 2, and 2 is not a boolean.
Converting values with bool()
The bool() constructor converts any object to True or False by applying Python's truthiness rules. The next chapter covers those rules fully. For now, remember a few cases:
print(bool([]), bool([0]), bool(""), bool("0"), bool(0.0), bool(None))
# False True False True False FalseEmpty containers, empty strings, zero, and None give False. Non-empty containers and non-empty strings give True, even the string "0" and the list [0]. These values are truthy because they are non-empty, not because of what they contain.
Common mistakes
- Comparing to True. Writing
if flag == True:is redundant. Writeif flag:. It is also less safe, because2 == TrueisFalseeven though2is truthy. - Expecting bool(str) to parse text.
bool("False")isTrue, since the string is non-empty. Compare the text instead:answer.lower() == "false". - Treating the result of arithmetic as a bool.
True + 1is2, anint.
How the pieces connect
Exercises
Exercise
What does the following code print? flags = [True, False, True, True] print(sum(flags), type(sum(flags))._name_, bool("False"))
Show answer
It prints 3 int True. sum() adds True as 1 and False as 0, giving the int 3. bool("False") is True because the string is non-empty.
Exercise
Why does len({1: "a", True: "b"}) return 1, and what is the value stored under the key?
Show answer
True == 1 and hash(True) == hash(1), so both keys are the same dictionary key. The second assignment replaces the value, so the single entry is {1: "b"}. The original key object 1 is kept.