Truth Value Testing
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
andFalse
. - zero of any numeric type: 0, 0.0, 0j, Decimal(0), Fraction(0, 1)
- empty sequences and collections: '', (), [], {}, set(), range(0)
>>> class A:
... def __bool__(self):
... return False
...
>>> a = A()
>>>
>>> bool(a)
False
>>> class B:
... pass
...
>>> b = B()
>>> bool(b)
True
__bool__
Called to implement truth value testing and the built-in operationbool()
; should returnFalse
orTrue
. When this method is not defined,__len__()
is called, if it is defined, and the object is considered true if its result is nonzero. If a class defines neither__len__()
nor__bool__()
, all its instances are considered true.__len__()
Called to implement the built-in functionlen()
. Should return the length of the object, an integer >= 0. Also, an object that doesn’t define a__bool__()
method and whose__len__()
method returns zero is considered to be false in a Boolean context.
Boolean Operations
x or y
: if x is false, then y, else x
This is a short-circuit operator, so it only 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, so it only evaluates the second argument if the first one is true.not x
: if x is false, thenTrue
, elseFalse
Note that neither and
nor or
restrict the value and type they return to False
and True
, but rather return the last evaluated argument. This is sometimes useful, e.g., if s is a string that should be replaced by a default value if it is empty, the expression s or 'foo'
yields the desired value. Because not
has to create a new value, it returns a boolean value regardless of the type of its argument (for example, not 'foo'
produces False
rather than ''
.
>>> 2 or 3
2
>>> 2 and 3
3
>>> s = ''
>>> s or 'foo'
'foo'
>>> not 'foo'
False
Comparisons
There are eight comparison operations in Python.
<
,<=
,>
,>=
,==
,!=
,is
,is not
x < y <= z
is equivalent tox < y and y <= z
, except that y is evaluated only once (but in both cases z is not evaluated at all when x < y is found to be false).
The
<
,<=
,>
and>=
operators will raise aTypeError
exception when comparing a complex number with another built-in numeric type, when the objects are of different types that cannot be compared, or in other cases where there is no defined ordering.Instances of a class cannot be ordered with respect to other instances of the same class, or other types of object, unless the class defines enough of the methods
__lt__()
,__le__()
,__gt__()
, and__ge__()
rich comparison methods
object.__lt__(self, other) ; xy calls x.__gt__(y)
object.__ge__(self, other) ; x>=y calls x.__ge__(y).
A rich comparison method may return the singleton NotImplemented
if it does not implement the operation for a given pair of arguments. By convention, False
and True
are returned for a successful comparison. However, these methods can return any value.
By default, __ne__()
delegates to __eq__()
and inverts the result unless it is NotImplement
.
- Identity comparisons
The operators is
and is not
test for object identity: x is y
is true if and only if x and y are the same object. Object identity is determined using the id()
function. x is not y
yields the inverse truth value.
>>> a = []
>>> b = []
>>> id(a) == id(b)
False
>>> a is b
False
>>> a is not b
True
>>> a = b = []
>>> id(a) == id(b)
True
>>> a is b
True
Numeric Types
There are three distinct numeric types: integers, floating point numbers, and complex numbers. In addition, Booleans
are a subtype of integers.
- some operations
x/y
: quotient of x and y
x//y
: floored quotient of x and y
x % y
: remainder of x / y
pow(x, y)
: x to the power y
x**y
: x to the power y
>>> 1 // 2
0
>>> -1 // 2
-1
>>> 0**0
1
>>> 0**1
0
>>> 1**0
1
>>> 2**0
1
-
inf
v.s.nan
inf
: positive infinity
-inf
: negative infinity
nan
: Not a Number
>>> a_inf = float('inf')
>>> b_nan = float('nan')
>>> 0 * a_inf
nan
>>> 2 * a_inf
inf
>>> -2 * a_inf
-inf
>>> 1 / a_inf
0.0
>>> import math
>>> math.isnan(b_nan)
True
>>> math.isinf(a_inf)
True
>>> b_nan == b_nan
False
>>> a_inf == a_inf
True