Home โบ Output practice โบ truthiness and the ternary
Predict the output: truthiness and the ternary
๐ฎ Predict the outputTopic: operatorsDifficulty: mediumNo login needed
The snippet
if x: does not ask whether x is a boolean; it asks whether x is *truthy*. Once you know the small list of false values, every other object โ including the string "0" โ is true.
count = 0
label = "ready" if count else "empty"
print(label, bool("0"), bool([]))
Your prediction
Type exactly what this program prints โ one line per print() call:
The output
empty True False
Verified against CPython 3.11 in this repo's build
Line-by-line explanation
count = 0
Zero is one of Python's few falsy values, socountis false in a condition.label = "ready" if count else "empty"
The condition is false โ theelsebranch โ"empty". Read the conditional expression in English order: *ready if count, else empty*.bool("0")Trueโ a non-empty string is truthy no matter what it contains, including"0"," "and"False".bool([])Falseโ empty containers are falsy (list, tuple, dict, set, str).printed togetherempty True False.
The rule you can reuse
Falsy: False, None, numeric zero of every type, and every empty sequence/collection. Everything else is truthy. Write if not items: rather than if len(items) == 0:.
Why most predictions break here
Calling bool("0") False because it prints as zero. Only the *number* 0 is falsy โ text of length 1 is not. And if count == False is a different question from if count.
Quick fire
Same rule, two more shapes. Predict first, then open.
Predict this too
print("yes" if [] else "no")
print(1 < 2 < 3, 3 > 2 > 1)Outputno
True True
An empty list is falsy โ no; comparison chaining means 1 < 2 and 2 < 3 โ True True.
Predict this too
print(not 0 and "ok")
print("" or "fallback")
print(5 and None)Outputok
fallback
None
and/or return an object, not a bool: ok, fallback, None.
Share your result
Challenge a friend โ the link contains the question, never the answer:
Copied โKeep practising this rule
More output questions โ All interactive problemsQuestions this page answers
Why do and/or return objects instead of True/False?
They short-circuit and hand back the value that decided the result โ which is what makes name = input() or "anonymous" work. Wrap in bool() when you need a real boolean.
Is 1 == True a trap too?
It is True, because bool is a subclass of int and 1 equals True. Use x is True only when you genuinely mean "that exact object", never for numbers.