Boolean Values and Truth Testing
A conditional converts its test to a truth value. Be precise about which values the condition treats as meaningful.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 2 min
In this article4 chapters
Learn the cases
An empty string and a numeric zero are false in Python. The string "0" is true because its length is one. Parsing input text before testing can therefore change which branch runs.
Pick the intended question
A function receives a queue of pending jobs. Testing the queue itself can answer whether any jobs remain. When a missing queue means that data loading failed, preserve that distinct outcome explicitly. Test the missing case and the valid empty queue, following the rules for unset and empty values.[1][2]
Ask which property a condition measures
A positive seat count, an existing booking, and a Boolean flag are different questions. In Python, if count runs for positive and negative nonzero integers. It will skip a literal zero. If eligibility requires at least one seat, the meaningful condition compares count with zero explicitly. A nonempty string such as "0" passes a truth test even though parsing it as a count produces a false numeric value. See parsing and domain validation for where that interpretation changes.
Keep an explicit check when false values are valid
Suppose a configuration uses zero for an intentionally disabled interval and None for unspecified. A truth test makes both cases false. Compare with None to select the default only in the missing case. Test a missing value, zero, and a positive input. This can reveal why a defaulting expression using or returns the same fallback for values intended to differ. And and or results explain that mechanism. Also check inputs your interface rejects before the condition runs. Accepting an invalid negative count and then observing it is truthy may lead to the right branch on one fixture for the wrong reason.