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
Tip: the highlighter is on - just select any text below to mark it. Use the highlighter button up top to change color or turn it off, saved just for you on this device.
You have 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 is 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. It is 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 is actually required: comparing against None, where it is 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 do not offer, and it reads exactly the way you would 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?
FizzBuzz, One Number at a Time
Write a function fizzbuzz_word(n) that returns "Fizz" if n is divisible by 3, "Buzz" if divisible by 5, "FizzBuzz" if divisible by both, and str(n) otherwise. The module's conditionals and comparison operators are exactly what this needs - no loops required, since the function only ever handles one number.