Boolean values and expressions¶
In Python, there are several ways to express Boolean values; the Boolean
constant False, 0, the Python type None and empty
values (for example the empty list [] or the empty string "") are all
considered False. The Boolean constant True and everything else is
considered True.
<,<=,==,>,>=compares values:
>>> x = 3 >>> y = 3.0 >>> z = [3, 4, 5] >>> x == y True
Warning
However, you should never directly compare calculated floating point numbers:
>>> u = 0.6 * 7 >>> v = 0.7 * 6 >>> u == v False >>> u 4.2 >>> v 4.199999999999999
Instead, you can use
math.isclose():>>> import math >>> math.isclose(u, v) True
Alternatively, you can also use
round():>>> round(u, 2) == round(v, 2) True
Warning
Integers smaller than -5 or larger than 256 are recreated each time, but integers in between are pre-instantiated by the interpreter and reused. Therefore,
id()should not be used for comparisons of integers:>>> x = 256 >>> y = 257 >>> id(x) == id(256) True >>> id(y) == id(257) False
is,is not,in,not inchecks the identity:
>>> x is y False >>> x is not y True >>> x in z True >>> id(x) 4375911432 >>> id(y) 4367574480 >>> id(z[0]) 4375911432
If
xandz[0]have the same ID in memory, this means that we are referring to the same object in two places.The
isoperator is mostly used for values that only exist once in memory, so-called singleton objects. For example, checking for None is the most common use of theisoperator.>>> x is None False >>> x is not None True
The Python style guide in PEP 8 also recommends that you should check for identity with None and not for values, so never use
x == None, but always usex is Noneinstead.and,not,orare logical operators that we can use to link the above checks:
>>> x is y and x is z[0] False >>> x is y or x is z[0] True >>> x is y and not x is z[0] False >>> x is z[0] and not x is y True