Boolean Truth Values
- VC Healy
- May 24, 2020
- 1 min read
Truth Value Testing
Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below.
By default, an object is considered true unless its class defines either a __bool__() method that returns False or a __len__() method that returns zero, when called with the object.
Here are most of the built-in objects considered false:
constants defined to be false: None and False.
zero of any numeric type: 0, 0.0, 0j, Decimal(0), Fraction(0, 1)
empty sequences and collections: '', (), [], {}, set(), range(0)
Operations and built-in functions that have a Boolean result always return 0 or False for false and 1 or True for true, unless otherwise stated. (Important exception: the Boolean operations or and and always return one of their operands.)
Boolean Operations — and, or, not
x or y if x is false, then y, else x
This is a short-circuit operator, it evaluates the second argument if the first one is false
x and y
if x is false, then x, else y
This is a short-circuit operator, it evaluates the second argument if the first one is true.
not x
if x is false, then True, else False
not has a lower priority than non-Boolean operators, so not a==b is interpreted as not(a==b), and a==not b is a syntax error.
Comentários