Truthiness, Comparisons & Boolean Logic
You'll learn to
- -Predict whether Python will treat any given value as true or false
- -Distinguish is from == and know when each is correct
- -Write chained comparisons like 0 < x < 10
You've been writing if conditions for two chapters now, mostly with explicit comparisons like age < 13. Python conditionals actually accept any value at all, not just booleans - which means it's worth knowing precisely which values Python treats as "false-ish" and which it treats as "true-ish."
What Counts as False?
- -The number 0 (and 0.0)
- -An empty string ""
- -An empty list [], empty dict {}, or empty set set()
- -None
- -The literal False itself
Every one of those is "falsy" - it behaves like False in a boolean context. Everything else - a non-zero number, a non-empty string, a non-empty collection - is "truthy." This lets you write conditions that read naturally instead of comparing against emptiness explicitly:
Writing "if my_list:" instead of "if len(my_list) > 0:" is the idiomatic Python style - shorter, and it works identically for strings, dicts, and sets too, not just lists.
is vs ==
== asks "do these two things have the same value?" is asks a stricter question: "are these two names pointing at the exact same object in memory?" For most day-to-day comparisons - numbers, strings, whether two lists contain the same items - you want ==. is has one place it's actually required: comparing against None, where it's the idiomatic and recommended form.
Chained Comparisons
Python lets you chain comparisons the way you would on paper - 0 < x < 10 really does mean "0 is less than x, and x is less than 10," evaluated as a single combined check. This is a genuine convenience most languages don't offer, and it reads exactly the way you'd expect.
When should you use is instead of ==?
"They're basically the same thing, I just use whichever."
"== compares values; is compares identity - whether two names refer to the literal same object in memory. Two separate lists with identical contents are == but not is. The one place is is actually required is comparing against None, since None is a singleton - 'if value is None' is the idiomatic check, and it also avoids surprises with custom objects that might override how == behaves."
Which of these values is falsy in Python?