Home      |       Contents       |       About

Prev: random & math modules      |      Next: Print


  • 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 [1]:
a = False
In [11]:
x = 0
b = bool(x)
b, type(b)
(False, bool)
In [14]:
a = 5
b = bool(a > 0)
  • 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 [35]:
a = 0
b = 0.0
c = []
d = [0]
e = ''

a == 0, b != 0, c <= [1], d is not False, e is '' 
(True, False, True, True, True)

Boolean Operators: and, or, not

In [40]:
x = True 
y = False

x and y, x or y, not x
(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 [37]:
x = y = True
a = b = False
(x or a) or (y and b)
  • 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