 Prev: random & math modules      |      Next: Print

# Booleans¶

• Booleans are implemented in Python as a subclass of integer, having only two values ("instance objects"): True and False

• A boolean obect can be constructed by: (a) assigning True or False to a name, or (b) calling the bool([x]) constructor

In :
a = False
type(a)

Out:
bool
In :
x = 0
b = bool(x)
b, type(b)

Out:
(False, bool)
In :
a = 5
b = bool(a > 0)
b

Out:
True
• In the above examples a boolean value True/False was assigned to b name, depending on the truth value of the expression that was passed as argument in the bool() constructor.
• This demonstrates that all objects in Python can be tested for their 'truth' value. Most of them are considered as 'True'. The following values are considered as 'False:
• None
• False
• zero of any numeric type, for example, 0, 0.0, 0j.
• Empty sequence (for example, empty list [ ], or empty string ' ')
• Empty mapping (for example, empty dictionary { })

#### Comparison Operators¶

• Comparison operators are used to write conditional expressions in control statements
• There are eight of them:
    <          less than
<=         less than or equal
>          strictly greater than
>=         greater than or equal
==         equal
!=         not equal
is         object identity
is not     negated object identity
In :
a = 0
b = 0.0
c = []
d = 
e = ''

a == 0, b != 0, c <= , d is not False, e is ''


Out:
(True, False, True, True, True)

#### Boolean Operators: and, or, not¶

In :
x = True
y = False

x and y, x or y, not x

Out:
(False, True, False)
• It's useful to remember that boolen operations are short-circuited, meaning that if a part of a boolean expression determines the value of the entire expression the remaining part is not computed
In :
x = y = True
a = b = False
(x or a) or (y and b)

Out:
True
• In the expression (x or a) and (y and b) first (x or a) is calculated. In the (x or a) expression first x is calculated. Since x is 'True' also (x or a) is true withut considering the a value. Eventually the entire expression is 'True' without any other part of the expression to be considered.  . Free learning material
. See full copyright and disclaimer notice