When And and Or Return Operands
Python's Boolean operators and and or return a selected operand, so the result need not have Boolean type.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 1 min
In this article4 chapters
Predict two examples
The result of "blue" or "gray" is the string "blue". With an empty first string it is "gray". That selection uses truth testing on the first operand, then evaluates the second only if the first is false.
Preserve zero if it matters
If a theme setting of zero means disable animation, duration or 200 selects 200 and loses the explicit choice. An absent-only default needs a separate test for the absence sentinel. See unset, empty, and zero values for designing that distinction.[1][2]
Trace the returned value through a fallback
In Python, preferred or fallback returns the first operand if it passes truth testing. Otherwise it evaluates and returns the second. If preferred equals the empty string and fallback equals "Untitled", the result is the latter string. If the preferred label is a nonempty string, the result is that string itself. This matters when the caller expects text or another specific type instead of a Boolean. See truth testing for which values trigger the choice.
Choose a representation that preserves deliberate settings
Suppose a user can set refresh seconds to zero to disable automatic updates and can omit the setting to use thirty seconds. An expression using refresh or 30 treats both values as a request for thirty. An explicit missing-value check can select thirty only for omission.
Try a test where the fallback expression increments a counter or raises a harmless exception. It should not run when the first operand supplies a satisfactory value. With and, a falsy first operand is returned and the later operand is skipped. See short-circuit evaluation for the execution rule behind both cases.