Sub topic 6
Truthiness: using values as conditions
This chapter assumes you can run Python scripts, know the basic data types (int, float, str, bool, list, dict, None), and have written a basic if/else statement.
What truthiness means
An if statement does not require a bool. Python accepts any value as a condition and converts it to True or False. A value that converts to True is called truthy. A value that converts to False is called falsy.
The rule is short. These values are falsy:
NoneandFalse- zero of any numeric type:
0,0.0,0j - empty sequences and collections:
'',[],(),{},set(),range(0)
Almost everything else is truthy, including non-zero numbers, non-empty strings, and non-empty containers. A user-defined object is truthy unless its class defines __bool__ or __len__ in a way that says otherwise.
You can check any value with bool():
for value in [0, 1, '', 'a', [], [0], {}, None, 0.0, ' ']:
print(repr(value), bool(value))Note that [0] and ' ' are truthy. The list has one element and the string has one character, so neither is empty. What the element is does not matter.
Testing for empty containers
Truthiness lets you skip an explicit length check:
items = []
if items:
print('has items')
else:
print('empty')This prints empty. The idiom if items: is preferred over if len(items) > 0: because it reads clearly and works for every container type.
Truthiness and short-circuiting
Truthiness combines well with and. Python stops evaluating an and expression as soon as it sees a falsy operand:
settings = {}
if settings and settings['debug']:
print('debug on')
else:
print('debug off')The empty dict is falsy, so settings['debug'] never runs. Without the first test, that lookup would raise a KeyError. The next chapters cover this behavior in detail.
Falsy is not the same as missing
Truthiness treats 0, '', and None the same way. That is a problem when zero is a legitimate value. Use is None to ask whether a value is missing:
count = 0
if not count:
print('zero or missing')
if count is None:
print('missing')
else:
print('a number was provided')This prints zero or missing and then a number was provided. The first test cannot tell the two cases apart. The second can.
The following diagram shows how Python decides.
Common errors
- Using
if x:when0or an empty string is a valid input. A function that accepts0as a quantity will wrongly reject it. Useif x is None:instead. - Assuming the string
'False'is falsy. It is a non-empty string, so it is truthy. Convert text to a real boolean before testing it. - Assuming
if x == True:is the same asif x:. The first is true only whenxequalsTrue, so2 == TrueisFalseeven though2is truthy. - Forgetting that
andandorreturn one of their operands, not always abool.[] or 'default'gives'default'.
Exercise
What does this code print, and why? name = '' if name is None: print('missing') elif not name: print('empty') else: print('named')
Show answer
It prints empty. The empty string is not None, so the first condition is False. The empty string is falsy, so not name is True and the elif branch runs.
Exercise
A function takes discount=None and should apply a discount of 0 when the caller passes 0 explicitly. Why is if discount: a bad test, and what should replace it?
Show answer
if discount: is False for 0, so an explicit zero is treated like a missing value. Use if discount is not None: so that only a missing value is skipped.