indusai.co

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

python
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

python
print(10 > 9)
print(10 == 9)
print(10 != 9)
print("apple" < "banana")   # strings compare alphabetically

Truthiness

Any value can be tested in a boolean context. Python treats these as false:

  • False and None
  • Zero of any numeric type: 0, 0.0, 0j
  • Empty collections: "", [], (), {}, set(), range(0)

Everything else is true.

python
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:.

python
items = []
if items:
    print("There are items")
else:
    print("The list is empty")

Combining booleans

python
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.

python
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

python
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.

python
votes = [True, False, True, True]
print(sum(votes), "yes votes")

Practice

  1. Without running it, predict the output of bool("0") and bool(0). Then run both.
  2. Write an expression that is true when a number n is between 1 and 100 inclusive.
  3. Use any() to check whether a list of marks contains any failing mark below 33.