Booleans
A boolean is either True or False. Booleans are what if statements and loops actually test, so nearly every program is full of them even when you do not write the words.
Boolean values
is_open = True
is_full = False
print(is_open, is_full)
print(type(is_open))Note the capital letters. true and false are not defined in Python.
Comparisons produce booleans
print(10 > 9)
print(10 == 9)
print(10 != 9)
print("apple" < "banana") # strings compare alphabeticallyTruthiness
Any value can be tested in a boolean context. Python treats these as false:
FalseandNone- Zero of any numeric type:
0,0.0,0j - Empty collections:
"",[],(),{},set(),range(0)
Everything else is true.
print(bool(0), bool(42))
print(bool(""), bool("hello"))
print(bool([]), bool([0]))
print(bool(None))This is why you can write if items: instead of if len(items) > 0:.
items = []
if items:
print("There are items")
else:
print("The list is empty")Combining booleans
age = 20
has_id = True
print(age >= 18 and has_id)
print(age < 18 or not has_id)
print(not True)and and or short circuit: they stop evaluating as soon as the answer is known and return the deciding value, not necessarily True or False.
print(0 or "default") # "default", because 0 is falsy
print("first" and "second")The x or default idiom is a common way to provide a fallback value.
Functions that return booleans
print(isinstance(5, int))
print(callable(print))
print("py" in "python")
print(all([True, True, False]))
print(any([False, False, True]))all() is true if every item is truthy; any() if at least one is.
Booleans are integers
True behaves like 1 and False like 0. This is occasionally useful for counting.
votes = [True, False, True, True]
print(sum(votes), "yes votes")Practice
- Without running it, predict the output of
bool("0")andbool(0). Then run both. - Write an expression that is true when a number
nis between 1 and 100 inclusive. - Use
any()to check whether a list of marks contains any failing mark below 33.
