Python 3 has a bool type representing Boolean values. There are two builtin bool constants, True and False.
For legacy reasons, bool is actually a subtype of int and True behaves like 1 while False behaves like 0.
For example,
>>> True + 0 1 >>> False * 3 0
and even...
>>> True == 1 TrueThe main difference between
True and 1 is that str(True) returns 'True' and not '1'. Similarly, str(False) returns 'False' and not '0'.
Any object can be converted to bool by running it through the bool constructor. Here are some examples:
>>> bool(True)
True
>>> bool(None)
False
>>> bool([])
False
For any object, x, if bool(x) is True, we say it's truth value is true and we consider x as true in a Boolean context. If bool(x) is 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
- If
x defines a __bool__ method that returns False or 0, it's false.
- If
x doesn'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:
- None
- False
- The zero value of each numeric type i.e.
0, 0.0, 0+0j
- Empty containers e.g.
(), {} and [].
- "" (the empty string)
0 comments:
Post a Comment