Truthiness & None
- Recognize what Python treats as truthy vs falsy
- Use
isvs==correctly, especially withNone - Handle empty containers, zero, and empty strings idiomatically
- Write concise conditionals using truthiness shortcuts
Python's falsy rules (0, '', [], {}, None all falsy) power idioms like if not users: and trip up devs from Java or C. None versus falsy is the source of countless bugs in Django form handling and API validation.
- Using
if x == None. PEP 8 mandatesif x is None;==can be overridden and give false positives. - Treating
0as missing data.if not count:triggers on bothNoneand0; useif count is Nonewhen zero is valid. - Assuming empty containers raise.
bool([])isFalse, soif my_list:cleanly guards against empty lists.
Python lets you ask if value: directly. The rule:
What's "falsy"
False,None0,0.0"",[],{},set()— empty containers
Everything else is "truthy".
is vs ==
==checks equality of valuesischecks identity (same object in memory)- Always use
isforNone:if x is None:
Try it
- Write a function that returns the first truthy item from a list, or
None. - What does
bool("False")return? Why?
3 graded exercises
Write the code, click Check. We’ll tell you exactly what to fix.
- Exercise 1
Given
data = [], print"empty"if the list is empty, otherwise print"has items". Use the Pythonic truthiness check (nolen(data) == 0). - Exercise 2
Given
x = None, print"missing"ifxis None, otherwise print its value. Use the correctischeck, not==. - Exercise 3
Write a function
first_truthy(items)that returns the first truthy value from a list, orNoneif there isn't one. Then printfirst_truthy([0, "", None, "hello", 5])— expected:hello.