Boolean Data Type
Boolean Data Type
The boolean data type is either True or False. In Python, boolean variables are defined by the
>>> a = True >>> type(a) <class 'bool'> >>> b = False >>> type(b) <class 'bool'>
<class 'bool'> indicates the variable is a boolean data type.
Note the keywords
False must have an Upper Case first letter. Using a lowercase
true returns an error.
>>> c = true Traceback (most recent call last): File "<input>", line 1, in <module> NameError: name 'true' is not defined >>> d = false Traceback (most recent call last): File "<input>", line 1, in <module> NameError: name 'false' is not defined
Integers and Floats as Booleans
Integers and floating point numbers can be converted to the boolean data type using Python's
bool() function. An int, float or complex number set to zero returns
False. An integer, float or complex number set to any other number, positive or negative, returns
>>> zero_int = 0 >>> bool(zero_int) False
>>> pos_int = 1 >>> bool(pos_int) True
>>> neg_flt = -5.1 >>> bool(neg_flt) True
Boolean arithmetic is the arithmetic of true and false logic. A boolean or logical value can either be
False. Boolean values can be manipulated and combined with boolean operators. Boolean operators in Python include
The common boolean operators in Python are below:
In the code section below, two variables are assigned the boolean values
False. Then these boolean values are combined and manipulated with boolean operators.
>>> A = True >>> B = False
>>> A or B True
>>> A and B False
>>> not A False
>>> not B True
>>> A == B False
>>> A != B True
Boolean operators such as
not can be combined with parenthesis to make compound boolean expressions.
>>> C = False >>> A or (C and B) True >>> (A and B) or C False
A summary of boolean arithmetic and boolean operators is shown in the table below:
|A||B||not A||not B||A == B||A =! B||A or B||A and B|