Beginner·14 min·0/47 done

Python Booleans

Learn True and False, comparisons, and how empty values behave.

Why it matters: Filtering scores and empty batches depends on truthiness.

Basics

True and False

Booleans have two values: True and False.

Comparisons return bools. bool(x) converts a value.

Falsy values: False, None, 0, 0.0, "", [], {}

Everything else is truthy. Common mistake: using if score: and dropping a valid 0.0.

Tiny example

Comparisons return bools.

print(10 > 9)
print(10 == 9)
print(bool("Hello"))
print(bool(""))

Basics

is vs ==

== compares values.

is compares identity (the same object in memory).

Use is only for None, True, and False. Use == for numbers, strings, and lists.

Tiny example

Use is for None. Use == for values.

api_key = None
print(api_key is None)
print(0.7 == 0.7)

Basics

and, or, any, all

and / or stop early when the result is known.

any(...) is True if at least one item is truthy. all(...) is True if every item is truthy.

Chained checks read clearly: 0.0 <= score <= 1.0.

Tiny example

Check a batch of scores.

scores = [0.9, 0.8, 0.7]
print(all(s >= 0.7 for s in scores))
print(any(s < 0.8 for s in scores))

Then AI / ML

AI / ML examples

Same idea, used in real AI work. Press Try in lab to run it.

AI / ML example

AI / ML: the 0.0 score bug

A real score of 0.0 is falsy but still valid.

In AI / ML: Probability outputs can be zero. Guard with is not None.

example.py

Python

score = 0.0
print(bool(score))
print(score is not None)

AI / ML example 2

AI / ML: batch checks

any and all judge a list of scores.

In AI / ML: Eval code uses any/all over scores to judge a batch.

example.py

Python

scores = [0.91, 0.72, 0.85]
print(all(s > 0.7 for s in scores))
print(any(s >= 0.9 for s in scores))

Takeaways

  • 1Falsy: False, None, 0, 0.0, "", [], {}.
  • 2Use is for None. Use == for values.
  • 3any() and all() check batches.
Certificate