Chapter 6

Booleans

Subsections of Booleans

Pseudocode Booleans

YouTube Video

Resources

In pseudocode, we can create variables that store values using the Boolean data type. These variables can only store one of two values: true or false. So, a Boolean value is really the simplest data value we can imagine - it is a single binary bit representing a value of true or false. In some systems, we may also refer to these values as 0 or 1, but in pseudocode we’ll just use true and false.

To create a variable that stores a Boolean value in pseudocode, we can use the following assignment statements:

x <- true
y <- false

In pseudocode, both true and false are keywords in the language. They represent the special boolean values true and false, and cannot be used as the name of a variable or procedure. Since they are values and not strings, we do not have to put them in quotation marks.

Converting Between Data Types

We can use the special BOOLEAN() procedure to convert any value to a Boolean value. Here are the basic rules for that conversion:

  • Strings: "true" will evaluate to true and "false" will evaluate to false. Capitalization doesn’t matter. All other values are undefined.
  • Numbers: 0 will evaluate to false, and any other value will be true.

The reverse works as well - Boolean values can be provided as input to the STRING() or NUMBER() procedures, and the outputs produced there will match these rules. Specifically, the true value will convert to the number $1$, but any non-zero number would be valid.

Subsections of Pseudocode Booleans

Pseudocode Operators

YouTube Video

Resources

There are also many special operators that can be used to perform operations on Boolean values. These operators are used to along with one or more Boolean values in some way to produce a resulting value. Let’s review the three important Boolean operators in pseudocode.

AND Operator

The first Boolean operator we’ll review is the AND operator. This operator is used to determine if both Boolean values are true, and if so the resulting value will also be true. Otherwise, it will be false. This corresponds to the following truth table:

Variable 1 Variable 2 Result
F F F
F T F
T F F
T T T

Here’s an example of using the AND operator in pseudocode:

x <- true
y <- true
z <- x AND y
DISPLAY(z)

When this code is executed, the following output should be displayed:

true

OR Operator

The next Boolean operator to review in pseudocode is the OR operator. This operator will result in a true value if at least one of the input values is true. If both inputs are false, then the result is false. This corresponds to the following truth table:

Variable 1 Variable 2 Result
F F F
F T T
T F T
T T T

Here’s an example of using the OR operator in pseudocode:

a <- true
b <- false
c <- a OR b
DISPLAY(c)

When this code is executed, the following output should be displayed:

true

NOT Operator

Finally, the other Boolean operator we’ll learn about is the NOT operator. This operator is only applied to a single Boolean value, and it is used to negate the value. This means that an input value of true will result in false, and vice-versa. This corresponds to the following truth table:

Variable 1 Result
F T
T F

Here’s an example of using the NOT operator in pseudocode:

x <- true
y <- NOT x
DISPLAY(y)

Once again, when this code is executed, we’ll see the following output:

false

These three operators allow us to perform the basic Boolean logic operations needed to build more complex programs.

Subsections of Pseudocode Operators

Pseudocode Comparators

YouTube Video

Resources

Another powerful feature of pseudocode are the comparator operators, which can be used to create Boolean values by comparing string and number values in an expression. These comparators are a powerful way to build programs that can perform different actions based on data received from the user, as we’ll see later in this lab. Let’s review the commonly used comparators in pseudocode.

Equal

The equal comparator = is used to determine if two values are equivalent. This operator can be used between any two values, and it will either result in a value of true if both values are equivalent, or false if they are not. Here are some rules to keep in mind:

  1. When comparing strings, the strings must be exactly identical to be equivalent. This means that capitalization, punctuation, and other special symbols must all be exactly the same in both strings.
  2. Strings and numbers will never be equivalent, even if the string contains text that would convert to the same numeric value. The same applies to strings and Boolean values.

For example, we can use the equal comparator to check if two numeric values are equivalent, as shown in this example:

x <- 5
y <- 3 + 2
DISPLAY(x = y)

When executed, this code will display the following output:

true

We can do the same for two strings:

a <- "Hello " + "World"
b <- "hello " + "world"
DISPLAY(a = b)

This time, the output will be:

false

This is because the two string values are not identical - one has capital letters, and the other one does not.

tip-1

In most other programming languages, the equality comparator is represented by two equals signs == instead of a single one =. This is because the single equals sign is used in assignment statements in most languages, so we use a double equal as the equality comparator to avoid any confusion between the two.

In pseudocode, we use the arrow symbol <- for assignment statements, so we can use the single equals sign for equality. However, it is important to remember that this only works in pseudocode, and will cause issues if used in other languages such as Python.

Not Equal

The next comparator is the not equal comparator, which is typically written as != in pseudocode. Sometimes, we may also see it formatted as the special character , but we won’t use that character in our pseudocode.

The not equal comparator is exactly what it sounds like - it will return true if the two values being compared are not equivalent, or false if the two values are equivalent. So, the statement a != b is the same as saying NOT (a = b).

Here’s an example of using this comparator in pseudocode:

x <- 5
y <- 5 + 0.000001
DISPLAY(x != y)

When executed on our “mental model” of a computer, we should get the following output:

true

This is because the values $5$ and $5.000001$ are not exactly the same value, even though they are very similar.

Less Than and Greater Than

The last four comparators are all similar, so we’ll cover them all as a group. These comparators are specifically used to compare the relationship between two values, determining an ordering between the two. We should already be familiar with these operators from mathematics:

  • < less than
  • <= less than or equal to (sometimes written as in text)
  • > greater than
  • >= greater than or equal to (sometimes written as in text)

When these comparators are applied to numeric values, they’ll compare the two values just like we’d expect from math. For example, we can see these comparators in action in this pseudocode:

a <- 5
b <- 6
DISPLAY(a < b)
DISPLAY("\n")
DISPLAY(a > b)

When we run this code, we’ll see the following output:

true
false

These comparators are a bit more confusing when applied to string values. In that case, they will look at the lexicographic order of the two strings, which is similar to alphabetical order but also includes capitalization, punctuation, and other special symbols. We won’t cover that in too much detail here, but in most computer programs the letters are sorted according to their order in the ASCII encoding standard.

For example, we can compare two strings as shown in this example:

x <- "test"
y <- "tent"
DISPLAY(x < y)

When we run this program in our “mental model” of a computer, we’ll see this output:

false

This is because the string "test" does not come before "tent" when placed in alphabetical order, since s comes after n. So, we would say that the string stored in x is not less than the string stored in y, and therefore the result should be false.

Order of Operations

It’s also important to note that there are many situations where Boolean operators and mathematical operators are used in the same expression. In those cases, the mathematical operators are all resolved first, and then the Boolean operators in this order, going from left to right:

  1. Boolean comparators
  2. NOT operator
  3. AND
  4. OR

As always, it is considered good practice to include parentheses in any complex expressions to make sure that the intent is clear, regardless of the order of operations.

Let’s look at a quick example in pseudocode:

x <- 4 < 5 AND 3 * 5 > 12 OR NOT 7 MOD 3 = 1

This expression includes many mathematical operators, as well as Boolean operators and comparators. To evaluate this expression, we must first resolve all mathematical operations first, so we’ll evaluate 3 * 5 and 7 MOD 3 and place those results in the expression:

x <- 4 < 5 AND 15 > 12 OR NOT 1 = 1

Next, we’ll resolve any comparator operators, moving from left to right. This will convert any remaining numbers into Boolean values. So, we’ll evaluate 4 < 5, 15 > 12, and 1 = 1 and replace those expressions with the resulting Boolean values:

x <- true AND true OR NOT true

Once we’ve done that, the next operator to evaluate is the NOT operator. So, we’ll evaluate NOT true to the resulting value false and place it back in the expression:

x <- true AND true OR false

Then, we’ll handle the AND operator, so we’ll evaluate true AND true to the value true:

x <- true OR false

Finally, we’ll evaluate the rest of the statement true OR false to the value true, which will be stored in the variable x:

x <- true

As we can see, the order of operations allows us to work through a complex expression like this example. However, in practice, it is always best to include parentheses where needed to make sure the expression is evaluated like we intend it to be.

Subsections of Pseudocode Comparators

Python Booleans

YouTube Video

Resources

In Python, Boolean values are stored in the bool data type. Just like in pseudocode, variables of the bool data type can only store one of two values, True or False.

To create a Boolean variable in Python, we can simply assign those values to a variable in an assignment statement:

a = True
b = False
print(a)
print(type(b))

When we execute that code, we’ll see the following output:

True
<class 'bool'>

In Python, we use the keywords True and False to represent Boolean values. Notice that they are capitalized, unlike the true and false values we saw in pseudocode. In Python, it is very important to make sure these values are capitalized, otherwise the program will not work properly. Also, since these are keywords and not strings, we don’t need to put them in quotation marks.

Converting Between Data Types

Python includes the special bool() function, which can be used to convert any data type into a Boolean value. The bool() function follows these rules to determine what to return:

  1. If the input is the value False, the value 0, the value None, or anything with 0 length, including the empty string, it will return False.
  2. Otherwise, for all other values it will return True.

Let’s look at a couple of quick examples. First, let’s try to convert the strings "True" and "False" to their Boolean equivalents:

print(bool("True"))
print(bool("False"))

When this code is executed, we’ll see this output:

True
True

This seems a bit strange, since the string "False" ended up creating the Boolean value True. However, if we look at the rules above, since the string "False" has a length greater than 1, and it is not any of the special values listed above, it should always result in the Boolean value True.

In this example, we can check a couple of special values using the bool() function:

print(bool(0))
print(bool(1))
print(bool(""))

In this case, we’ll see the following output:

False
True
False

Here, we see that the value 0, as well as the empty string "", both result in a value of False. However, the value 1 is True, since it is a non-zero value.

In practice, we won’t use the bool() function directly very often. Instead, if we want to determine if a user inputs a True or False value, we can just use one of the Boolean comparators that we’ll see later in this lab.

Subsections of Python Booleans

Python Operators

YouTube Video

Resources

Python also includes several operators that can be applied to one or two Boolean values. These operators make up the basis of Boolean logic, and allow us to construct complex expressions of Boolean values. Let’s quickly review the three basic Boolean operators present in Python.

And Operator

In Python, we use the keyword and to perform the Boolean and operation. Just like in pseudocode, this operator will return True if both input values are also True, otherwise it will return False.

Here’s a quick example of the and operator in Python:

x = True
y = False
print(x and y)

When we run this Python code, we should see this output:

False

Since the variable y is False, the resulting value is also False.

Or Operator

Likewise, the keyword or is used in Python for the Boolean or operation. This operator will return True if either of the input values is True, but it will return False if neither of them are True.

Let’s look at an example:

a = False
b = True
print(a or b)

When we execute this code, we’ll get this output:

True

Since b is True, we know that at least one input is True and the result of a or b is also True.

Not Operator

Finally, Python uses the keyword not to represent the Boolean not operation, which simply inverts a Boolean value from True to False and vice-versa.

Here’s an example:

x = True
print(not x)
print(not not x)

When we run this code, we’ll see this printed to the terminal:

False
True

Since x is True, we know that not x is False. We can then perform the not operation again, on that result, as shown in not not x, which will result in the original value of x, which is True.

Subsections of Python Operators

Python Comparators

YouTube Video

Resources

Python also uses various comparators to allow us to compare values of many different data types to produce a Boolean value. We can compare numbers, strings, and many other data types in Python using these comparators.

Since we’ve already covered the comparators in pseudocode, let’s just briefly go over all of them and discuss any ways they differ in Python compared to pseudocode.

The basic comparators in Python are:

  • == equal
  • != not equal
  • < less than
  • <= less than or equal to
  • > greater than
  • >= greater than or equal to

Notice that the equal comparator in Python now uses two equals signs == instead of a single one. This is because the single equals sign = is used in the assignment statement, and we don’t want to confuse a Boolean comparator for an assignment. So, in Python, as in most other programming languages, we use two equals signs == when comparing values, and one equals sign = when we are storing a value in a variable.

Comparing values

Just like in pseudocode, we usually only want to compare values of the same data type using comparators. It really only makes sense to compare strings to strings, and booleans to booleans. However, for the numeric data types int and float, we can easily compare values of either data type together in Python.

Consider the following example:

x = 5
y = 5.0
print(x == y)

When we execute this code, we’ll get this output:

True

Even though x is the int data type and y is the float data type, they both store the same numerical value, and our comparators will work just like we expect. So, we can easily compare both integers and floating-point values in our code.

note-1

Behind the scenes, when we compare an int and a float value in Python, Python will convert the values to a common data type, usually the float data type, using the appropriate conversion function. This is known as coercion in programming - the program is essentially forcing a value of one data type into another data type because of an operation. However, it won’t change the data type of the variable involved, just the value it is evaluating.

Strings in Python can also be compared using the various comparator operators. When two strings are compared using any type of “less than” or “greater than” comparator, they will be compared according to their lexicographic order . In general, this means that each letter will be ordered based on its value in the ASCII encoding standard.

Let’s look at a quick example:

a = "First"
b = "fir"
print(a < b)

When we run this code, we’ll see this output:

True

This may seem surprising, since we’d expect the word "fir" to come before the word "First" in a dictionary, since it has fewer letters. However, in Python, the letters "f" and "F" are not treated identically. According to the ASCII encoding standard, capital letters have a lower value than lower-case letters, so all words starting with a capital "F" will come before any words starting with a lower-case "f".

This can be a bit confusing, so it is always important to remember that we can always write a quick sample program in Python to test how a particular operator will work for a given set of values. If nothing else, we can always count on our computer to produce the same result for the same operation, no matter if it is part of a larger program or a small test program.

Order of Operations

Finally, Python’s order of operations follow the same rules that we saw in pseudocode. So, when we see an expression that combines mathematical operators with Boolean operators and comparators, we’ll follow this order:

  1. Math operators (according to their order of operations)
  2. Boolean comparators
  3. not operator
  4. and operator
  5. or operator

As always, it is considered good practice to include parentheses in any complex expressions to make sure that the intent is clear, regardless of the order of operations.

Subsections of Python Comparators

Summary

In this lab, we covered several major important topics. Let’s quickly review them.

Booleans in Pseudocode

  • true
  • false
  • BOOLEAN() procedure to convert values
    • 0 is false, and any other number is true

Pseudocode Boolean Operators

  • AND
  • OR
  • NOT

Pseudocode Boolean Comparators

  • = equal
  • != not equal
  • < less than
  • <= less than or equal to
  • > greater than
  • >= greater than or equal to

Booleans in Python

  • True
  • False
  • bool() procedure to convert values
    • If the input is the value False, the value 0, the value None, or anything with 0 length, including the empty string, it will return False.
    • Otherwise, for all other values it will return True.

Python Boolean Operators

  • and
  • or
  • not

Python Boolean Comparators

  • == equal
  • != not equal
  • < less than
  • <= less than or equal to
  • > greater than
  • >= greater than or equal to

Comparators and Strings

Strings are compared using lexicographic order

Boolean Order of Operations

  1. Math operators (following their order of operations)
  2. Boolean comparators
  3. not
  4. and
  5. or