17. Boolean logic in depth — Homework solutions

The .py solution files are in exercises/17/homework/solutions/.

Problem 1 — Default colour

Problem. Fall back to "blue" when fav is None.

Worked solution.

fav = None                   # try a real colour here too
colour = fav or "blue"
print("Your colour is " + colour)

With fav = None it prints Your colour is blue; with fav = "red" it prints Your colour is red.

Common mistakes.

  • Writing if fav is None: colour = "blue" else colour = fav. Correct, but fav or "blue" is the shorter idiom worth knowing.

Problem 2 — Truthy table

Problem. Show whether each value is truthy using bool(value).

How to think about it. bool() converts any value to True or False according to Python's truthy/falsy rules.

Worked solution.

print(0, bool(0))         # 0      False
print("", bool(""))       #        False
print(None, bool(None))   # None   False
print(False, bool(False)) # False  False
print("hi", bool("hi"))   # hi     True
print(1, bool(1))         # 1      True

In Python, 0 and "" are falsy.

Problem 3 — Guarded division

Problem. Print the average only when count is above zero.

Worked solution.

total = 90
count = 0                    # try a real number too

if count > 0 and total / count > 0:
    print("Average: " + str(total / count))
else:
    print("no data")

With count = 0 the count > 0 test is False, so Python short-circuits and skips the division, printing no data. With count = 3 it prints Average: 30.0.

Common mistakes.

  • Writing if total / count ... without the count > 0 guard. The division then runs even when count is 0 — that raises a ZeroDivisionError. The guard prevents it.

Challenge — First value that exists

Problem. Print the first of a, b, c that is not None.

Worked solution.

a = None
b = None
c = "third"

print(a or b or c or "none")     # third

or runs left to right and returns the first truthy value, so the chain lands on the first variable holding something. If all three are None, it returns the final "none".

Common mistakes.

  • A long if/elif ladder checking each for None. Correct, but the or chain does it in one line.

Done?

You now know that and/or return values, short-circuit, and power the x or default trick. Next is Loops, the other way to make a program do more than the same thing each time.