Boolean Expressions
Python has boolean expressions that can take on the values True and False. They are most frequently seen in if-statements.
Often, we use comparison operators in order to create boolean expressions. The operators are:
== | Test for equality |
< | Test for being smaller |
<= | Test for being smaller or equal |
> | Test for being greater |
>= | Test for being greater or equal |
!= | Test for inequality |
The tests for equality and inequality can be quite difficult for non-numeric operands, but we do not need to worry about this yet.
Of more importance is that we can combine boolean conditions using boolean
operators, namely "and", "or", and "not". New in the latest Python version
is the possibility to "chain comparisons". For example
if 1 < x <10:
was previously only possible to write as
if 1 < x and x < 10
. Instead of using the English words
and
, or
, or not
, we can also use the
operators known from other programming languages, namely &&
,
||
, and !
. To define precedence, we can use
parentheses.
One interesting feature of Python that can be abused to write difficult to
read code is that every object has a Boolean value. An object evaluates to
False if it is None, 0 (for a numerical value), an empty collection, or has
a special user-defined method that says that it is empty. At this point, the
only relevant example is that of an expression that evaluates to 0. For
example, if we say if x % 2 :
, then x % 2
is evaluated as a Boolean. If x % 2
is zero, i.e. if x is
divisible by two, then the expression x % 2
evaluates to False,
and if x is odd, then the expression x % 2
evaluates to True.