Boolean is a datatype named after George Boole (1815-1864). A Boolean variable can take only two values, True
or False
. The main use of this type is in logical expressions. Here are some examples:
a = True b = 30 > 45 # b gets the value False
Boolean expressions are often used in conjunction with the if
statement:
if x > 0: print("positive") else: print("nonpositive)
Boolean operations are performed using the and
, or
, and not
keywords in Python:
True and False # False False or True # True (30 > 45) or (27 < 30) # True not True # False not (3 > 4) # True
The operators follow some precedence rules (refer to section Executing scripts in Chapter 1, Getting started) which would make the parentheses in the third line and in the last obsolete (it is a good practice to use them anyway to increase the readability of your code). Note that the and
operator is implicitly chained in the following Boolean expressions:
a < b < c # same as: a < b and b < c a == b == c # same as: a == b and b == c
Rules of Conversion to Booleans:
Table 2.2 : Rule of conversion to Boolean
Most objects Python may be converted to Booleans; this is called Boolean casting. The built-in function bool
performs that conversion. Note that most objects are cast to True
, except 0
, the empty tuple, the empty list, the empty string, or the empty array. These are all cast to False
.
It is not possible to cast arrays into Booleans unless they contain no or only one element; this is explained further in Chapter 5, Advanced Array Concepts. The previous table contains summarized rules for Boolean casting. Some usage examples:
bool([]) # False bool(0) # False bool(' ') # True bool('') # False bool('hello') # True bool(1.2) # True bool(array([1])) # True bool(array([1,2])) # Exception raised!
Using an if
statement with a non-Boolean type will cast it to a Boolean. In other words, the following two statements are always equivalent:
if a: ... if bool(a): # exactly the same as above ...
A typical example is testing whether a list is empty:
# L is a list if L: print("list not empty") else: print("list is empty")
An empty array, list, or tuple will return False
. You can also use a variable in the if
statement, for example, an integer:
# n is an integer if n % 2: print("n is odd") else: print("n is even")
Note that we used %
for the modulo operation, which returns the remainder of an integer division. In this case, it returns 0
or 1
as the remainder after modulo 2
.
In this last example, the values 0
or 1
are cast to bool
. Boolean operators or
,and
, and not
will also implicitly convert some of their arguments to a Boolean.
Note that the operators and
and or
do not necessarily produce Boolean values. The expression
x and y
is equivalent to:
def and_as_function(x,y): if not x: return x else: return y
And the expression x or y
is equivalent to:
def or_as_function(x,y): if x: return x else: return y
Interestingly, this means that when executing the statement True or x
, the variable x
need not even be defined! The same holds for False and x
.
Note that, unlike their counterparts in mathematical logic, these operators are no longer commutative in Python. Indeed, the following expressions are not equivalent:
[1] or 'a' # produces [1] 'a' or [1] # produces 'a'
In fact, Booleans and integers are the same. The only difference is in the string representation of 0 and 1 which is in the case of Booleans False
and True
respectively. This allows constructions like this (for the format method refer section on string formatting):
def print_ispositive(x): possibilities = ['nonpositive', 'positive'] return "x is {}".format(possibilities[x>0])
We note for readers already familiar with the concept of subclasses, that the type bool
is a subclass of the type int
(refer to Chapter 8, Classes). Indeed, all four inquiries isinstance(True, bool)
, isinstance(False, bool)
, isinstance(True, int)
, and isinstance(False, int)
return the value True
(refer to section Type Checking in Chapter 3, Container Types).
Even rarely used statements such as True+13
are syntactically correct.
3.149.249.252