Lesson 09 - Boolean Variables

The following topics are discussed in this notebook:

  • An introduction to the boolean data type.
  • Comparisons
  • Comparing different data types.
  • Arithmetic with boolean values.

Introduction to Boolean Values

When writing a program to automate a task, it is often necessary for the program to be able to check whether or not a certain logical condition is true, and then select an action based on this evaluation. As a tool for working with evaluation logical expressions, Python provides us with a Boolean data type. Boolean variables can take only one of only two values: True or False.

In the next two cells, we will create two boolean variables. For each variable, we will print its value, as well as its type.

In [1]:
varT = True
print(varT)
print(type(varT))
True
<class 'bool'>
In [2]:
varF = False
print(varF)
print(type(varF))
False
<class 'bool'>

Comparison Operators

Provide provides many comparison operators for checking to see if certain relationships exist between two values. Each comparison operator will evaluate as single Boolean value. The most commonly used comparison operators are:

Operator Meaning
< Less than
> Greater than
<= Less than or equal to
=> Greater than or equal to
== Equal to
!= Not equal to

Note that the "equal to" comparison operator (==) consists of two equals signs, while the assignment operator (=) consists of one equal sign. Mixing up these operators is a very common mistake, even for experienced programmers.

When one of the comparison operators appears between two values, Python will perform the indicated comparison, which will evaluate to either True or False.

Numerical Comparisons

Comparison operators are most commonly used to compare numerical values. When used between two numbers, as comparison operator will have the same meaning as the associator comparison from mathematics. Let's see some examples.

In [3]:
# Less than
2 < 6
Out[3]:
True
In [4]:
# Greater than
2 > 9
Out[4]:
False
In [5]:
# Equality operator
1 == 7
Out[5]:
False
In [6]:
6 == 2*3
Out[6]:
True
In [7]:
# Not equal
6 != 10 - 3
Out[7]:
True

All of the comparison examples above involved comparisons between integers. It is worth mentioning that Python will compare integers and floats without complaint.

In [8]:
a = 17
b = 17.0

print(type(a))
print(type(b))
<class 'int'>
<class 'float'>
In [9]:
a == b
Out[9]:
True

String Comparisons

We can also perform comparisons between strings. In this case, a Python performs a lexicographical comparison in which strings are ordered alphabetically, with letters appearing earlier in the alphabet being "less than" those later in the alphabet. The comparison is case sensitive, with uppercase letters appearing before lowercase letters in the ordering.

In [10]:
'zebra' > 'aardvark'
Out[10]:
True
In [11]:
'aardvark' < 'ant'
Out[11]:
True
In [12]:
'aardvark' < 'Bat'
Out[12]:
False
In [13]:
'Ant' == 'ant'
Out[13]:
False

If you ever wish to compare two strings in a case-insensitive way, then you can first convert both strings to lowercase using the lower() string method.

In [14]:
s1 = 'Zebra'
s2 = 'zebra'

s1.lower() == s2.lower()
Out[14]:
True

Python has a few special comparison operators that can be used to detect specific types of relationships between strings. For example, strings can be compared using the in and not in operators.

  • The in operator will return True if the string on the left side of the operator appears within the string on the right side, and False otherwise.
  • The not in operator will return True if the string on the left of the operator DOES NOT appear within the string on the right side, and False otherwise.
In [15]:
my_string = 'This land is my land.'

print('land' in my_string)
print('island' in my_string)
print('Land' not in my_string)
True
False
True

Comparings Strings and Integers

In some situations, it is valid to use the comparison operators between values of different data types. Although (with the notable exception of comparisons between int and float values) the results are often not that interesting.

For example, you can use != and == to compare a string with a numerical value, but Python will always interpret the two items as being unequal, regardless of the values.

In [16]:
str7 = "7"
int7 = 7

str7 == int7
Out[16]:
False

Attempting to compare a strings with a number using <, >, <=, or >= will produce an error.

In [17]:
str7 < int7
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-17-d1a71b3d6a42> in <module>
----> 1 str7 < int7

TypeError: '<' not supported between instances of 'str' and 'int'

Arithmetic with Boolean Values

Boolean values can be used in expressions as if they were numbers. When used in a numerical calculation, Boolean Values are evaluated as follows:

  • 'True' evaluates to 1
  • 'False' evaluates to 0

We illustrate this concept with a few examples below.

In [18]:
False + True
Out[18]:
1
In [19]:
False * True
Out[19]:
0
In [20]:
True * 2
Out[20]:
2
In [21]:
False * 5
Out[21]:
0
In [22]:
True + 5
Out[22]:
6

It might seem strange to assign logical values a numerical interpretation, but it is quite common within mathematics and computer science. And, as we will see later, it does have a number of useful applications.

Logical Operators

We can use the logical operators (or Boolean Operators) and, or, and not to perform a certain kind of arithmetic on Boolean values. These rules for evaluating these operators are as follows:

  • When and appears between two Boolean values, it will evaluate to True if and only if both Boolean values are True. If either value is False, then the and operator will evaluate to False.

  • When or appears between two Boolean values, it will evaluate to True if either of the Boolean values are True. If both values are False, then the or operator will evaluate to False.

  • When not appears before a Boolean value, it will perform a logical negation, evaluating to the opposite Boolean value.

The cells below cover all of the possible cases that can arise from using these operators on Boolean values.

In [23]:
# Truth values for and operator
print(True and True)
print(True and False)
print(False and True)
print(False and False)
True
False
False
False
In [24]:
# Truth values for or operator
print(True or True)
print(True or False)
print(False or True)
print(False or False)
True
True
True
False
In [25]:
# Truth values for not operator
print(not True)
print(not False)
False
True

We can use the logical operators to combine basic conditional expressions into more complicated expressions.

In [26]:
x = 7
print( (x > 2) and (x < 9) )
print( (x > 2) and (x < 6) )
True
False
In [27]:
print( (x > 2) or (x < 6) )
print( (x > 9) or (x < 6) )
True
False
In [28]:
print( not (x < 9))
False

Modulus Operator

The modulus operator % can be used to find the remainder resulting from dividing one integer by another. If a and b are integers, then the expression a % b will evaluate to the remainder resulting from dividing a by b.

In [29]:
print(37 % 5)
2
In [30]:
print(38 % 5)
3

We can use the modulus operator to determine if one number is evenly divisible by another.

In [31]:
x = 42
print(x % 7 == 0)
True
In [32]:
x = 32
print(x % 7 == 0)
False
In [33]:
x = 17
print((x > 5) and (x % 2 == 1))
True