Python 3 has a
bool type representing Boolean values. There are two builtin
For legacy reasons,
bool is actually a subtype of
True behaves like
False behaves like
>>> True + 0 1 >>> False * 3 0
>>> True == 1 TrueThe main difference between
Any object can be converted to
boolby running it through the
boolconstructor. Here are some examples:>>> bool(True) True >>> bool(None) False >>> bool() False
For any object,
True, we say it's truth value is true and we consider
xas true in a Boolean context. If
False, we say it's truth value is false and we consider it as false in a Boolean context.
x's truth value is determined as follows:
- If x is
None, it's false
__bool__method that returns
0, it's false.
xdoesn't define a
__bool__method but defines a
__len__method that returns 0, it's false.
- Otherwise, it's true
Given the rules above, it's no surprise that the vast majority of objects are considered true. The main ones that are considered false are:
- The zero value of each numeric type i.e.
- Empty containers e.g.
- "" (the empty string)