Booleans

Comparisons, and/or/not, and truthiness.

True and False are the results of comparisons. Use them in if (next chapter) and to filter data.

Goal

Compare values, combine with and / or / not, and see which objects count as false.

Comparisons

print(3 > 2)
print(3 == 3)
print(3 != 2)
print("Ada" == "ada")
print("Ada" < "Alan")

String order is lexicographic (Unicode). Case matters.

Combine

score = 91
print(score >= 90 and score < 95)
print(score < 50 or score >= 90)
print(not score < 50)

and / or short-circuit: the right side runs only if needed.

Truthiness

These are false: False, None, 0, 0.0, "", [], {}, set(). Everything else is true.

print(bool(0), bool(1), bool(""), bool("Ada"), bool([]), bool([0]))

in

print("ai" in "Nairobi")
print(3 in [1, 2, 3])
print("score" in {"name": "Ada", "score": 98})

On a dict, in checks keys.

Pitfall

== compares values. is compares identity (same object). Use is for None: x is None, not x == None.

x = None
print(x is None)
print(x == None)