Learn about logical operators and truth tables. Also learn how to write a Scratch program that illustrates the use of the logical and, or, and not operators when used in conjunction with relational operators.
Published: May 7, 2008
Last Revised: May 16, 2008
By Richard G. Baldwin
Homeschool Programming Notes # 110
This tutorial lesson is part of a continuing series that is designed specifically for teaching computer programming to homeschool students and their parents. However, even though the series is designed for homeschool students, everyone is welcome to use the lessons to learn computer programming.
In this lesson, I will provide an explanation of logical operators and truth tables. Then I will present and explain a Scratch program that illustrates the use of the logical and, or, and not operators when used in conjunction with relational operators. You learned about relational operators in an earlier lesson (see Resources).
Finally, I will provide the specifications for two programming projects for you to demonstrate your understanding of what you learned from the first program and from earlier lessons. One of the programming projects is relatively difficult requiring an understanding of DeMorgan's theorem (see Resources).
Copies of all three programs will be posted online for your review (see Resources for the URL). If you don't find the program using that URL, search the Scratch site for the user named dbal.
I recommend that you open another copy of this document in a separate browser window and use the following links to easily find and view the figures while you are reading about them.
I recommend that you also study the other lessons in my extensive collection of online programming tutorials. You will find a consolidated index at www.DickBaldwin.com.
There are many different kinds of operators. The easiest way to study them is to divide them into categories such as the following
Earlier lessons explained arithmetic operators and relational operators. This lesson will explain logical operators. Future lessons will deal with the remaining two kinds of operators.
In this lesson, I will present and explain a Scratch program named Logical01. This program illustrates the use of the and, or, and not operators in Scratch. These are called logical operators.
A real-world example
Logical operators can be confusing at first glance, but perhaps a real world example will help to eliminate some of that confusion. For many years in this country, we have had a movie rating system designed to control the viewing of objectionable content by young people. According to Wikipedia, the R rating means something like the following:
"Restricted - Under 17 requires accompanying parent or adult 17 or older with photo ID"
Formulate this using logical operator concepts
In most cases, this means that a person will be allowed entry into the theatre to view the movie if:
Note the use of the boldface Italicized words or and and in the above example.
The not operator
The not operator is a little more difficult to explain in terms of real world examples. At this point, suffice it to say that the application of the not operator causes something that is true to become false and causes something that is false to be come true. For example, if someone is older than 16, that person is not 16 or younger.
The reality - logic in a formal sense
The reality is that you have been dealing with this kind of logic most of your life. However, unless you had a specific reason to do so, such as being a computer programmer, a computer engineer, or perhaps an attorney, you may never have thought about it in a formal sense. The time to think about it in a formal sense has now arrived.
This program creates the following seven variables, displays them on the Stage, and initializes them all to zero when the user clicks the green flag as shown in Figure 1. (Note that unlike Java, spaces and characters other than numbers and letters are allowed in variable names in Scratch.)
Figure 1. Reduced screen shot of program named Logical01.
The range of each slider variable is set to -10 to 10. A button is also displayed on the Stage as shown in Figure 1.
Three event handlers, which are partially visible as scripts in the center panel in Figure 1, are written for when button clicked.
At runtime, the user adjusts the value of each of the first four variables in the above list using a slider.
When the user clicks the button, each event handler evaluates a relational-logical expression (an expression containing both relational and logical operators) corresponding to the name of one of the boldface variables in the above list. If the expression evaluates to true, a value of 1 is displayed in the corresponding variable. If the expression evaluates to false, a value of 0 is displayed.
Meaningful variable names
In an earlier lesson, I told you that you should always strive to use meaningful variable names. At this point, you are probably thinking that variables named A, B, C, and D aren't very meaningful, and if so, your thinking is correct. However, there is a good practical reason that I didn't use meaningful variable names in this case.
Really meaningful variable names usually require about five or more characters. If I had used longer names for the variables in this program, the expressions containing those variable names simply wouldn't have fit in the width of the center panel in Figure 1. In that case, a horizontal slider would have been automatically created for the center panel by the user interface. Unfortunately, as near as I can tell, the sizes of the various panels in the Scratch user interface are fixed and cannot be changed by the programmer.
Meaningful visual scripts versus meaningful variable names
If the scripts in the center panel are so wide as to require the user to scroll horizontally to view them in their entirety, it is extremely difficult to publish meaningful images of those scripts in documents such as this one. (See Figure 7 for example.) Therefore, in this case I opted for meaningful visual scripts at the expense of meaningful variable names for the first four variables in the above list.
You will note, however, that the last three variable names in that list are very meaningful. In fact they are probably more meaningful than would be the case in Java because Java doesn't allow the space character, the "<" character, or the "(" character to be included in a variable name.
A truth table
According to Wikipedia:
"A truth table is a mathematical table used in logic — specifically in connection with Boolean algebra, boolean functions, and propositional calculus — to compute the functional values of logical expressions on each of their functional arguments, that is, on each combination of values taken by their logical variables. In particular, truth tables can be used to tell whether a propositional expression is true for all legitimate input values, that is, logically valid."
What does this mean?
The concept of a truth table simpler than the above quotation might suggest. Figure 2 is a simple truth table that shows the result of evaluating four logical expressions for all combinations of the values of two variables, A and B, where each variable can only take on the values of true and false.
Figure 2. A simple truth table.
|A||B||(A and B)||(A or B)||not(A and B)||not(A or B)|
The and operation
If both A and B are true, then the expression (A and B) evaluates to true. Otherwise, it evaluates to false. Correspondingly, if (A and B) is true, then not(A and B) is false. Otherwise, it is true. Applying the not operator to a boolean value is often referred to as getting the compliment of that value.
The inclusive or operation
The operation that I am getting ready to discuss in known as an inclusive or operation. There is also an exclusive or operation that I won't discuss in this lesson. That will be a topic for a much more advanced lesson.
If either A or B are true, then the expression (A or B) evaluates to true. Otherwise, it evaluates to false. Correspondingly, if (A or B) is true, then not(A or B) is false. Otherwise it is true.
A practical example
Figure 3 is a truth table that shows some of the possible results produced by the logic used in the program named Logical01.
Figure 3. A truth table for the logic in the program named Logical01.
Evaluation against trial values
On any given row in Figure 3, the four columns labeled A, B, C, and D show trial values that can be assigned to the corresponding variables having the same names in the program. Each of the rightmost three columns on that row shows the result of evaluating the relational-logical expression at the top of the column.
Let's walk through this
Let's walk across the row labeled 2. Although the value of C is algebraically less than the value of D, the value of A is not less than the value of B because the two have equal values. As a result, the expression ((A<B)and(C<D)) evaluates to false. Both operands of an and operator must be true for the entire expression to be true. Correspondingly, the complement of that value shown in the next column is true.
Even though the value of A is not less than the value of B for row 2, the value of C is less than the value of D. Therefore, the value of ((A<B)or(C<D)) is true. Only one operand of an inclusive or operator must be true for the entire expression to be true.
Can become very complex
Although not illustrated here, extremely complex logical expressions can be constructed by using parentheses for grouping terms and applying a combination of and operators and or operators.
Figures 4, 5, and 6 show screen shots of the upper-left portion of the Stage area in Figure 1 for different combinations of values for the slider variables A, B, C, and D. The values for the four variables in each of the three figures correspond to the values assigned to the corresponding columns in Figure 3.
Recall that this program produces an output value of 1 for true and 0 for false. Then compare the output values in each figure with the values shown in the corresponding columns in Figure 3.
Figure 4. Program output for row 1 in Figure 3.
Figure 5. Program output for row 2 in Figure 3.
Figure 6. Program output for row 3 in Figure 3.
Figure 7. Center panel for the program named Logical01.
Compare Figure 7 with Figure 3
If you compare the relational-logical expressions defined by the statements in the green areas of Figure 7 with the expressions in the column headers in Figure 3, you should see a strong resemblance.
Parentheses are used to eliminate ambiguity and to clearly identify the operands of each operator in Figure 3. A 3D optical illusion is used for the same purpose in Figure 7. For example, it appears that everything to the right of the not operator in Figure 7 is a little closer to the viewer than the green platform on which the word not is printed.
No detailed explanation of the construction is required
In the past several lessons, I have walked you through the detailed drag, drop, insert, and typing steps required to produce scripts similar to those shown in Figure 7. Hopefully, you understand the mechanics of that process by now and it should no longer be necessary for me to walk you through the process.
Program behavior at runtime
The user begins by clicking the green flag in the upper right of Figure 1 to initialize all of the variables shown in Figure 4 to zero. Then the user can change the value in each of the variables A, B, C, and C by moving the sliders shown in Figure 4.
Order of execution of scripts
Following that, when the user clicks the button at the bottom of Figure 4, each of the bottom three scripts in Figure 7 is executed. Note that they are not all executed simultaneously due to practical limitations in the construction of most computers. However, I can't tell you the exact order in which they are executed because, as far as I know, that is not public information. It might be logical to assume that the individual scripts are executed from top to bottom, but such an assumption may not be correct.
Not important in this program
The order in which the three scripts are executed doesn't really matter in this program because the end result will be the same regardless of the order of execution. However, if two different scripts were to make modifications to the value of the same variable, the order in which those modifications are made could matter a lot. I mention this simply as a word to the wise. Be careful and make certain that you don't write different event handlers that respond to the same event and modify the same data in different ways even if that seems to appeal to your organizational sensibilities. In that case, you should combine the different event handlers into a single event handler because the order of execution of the code within a script is well defined.
Evaluate the relational-logical expressions and take appropriate action
For each of the bottom three scripts in Figure 7, if the relational-logical expression given by the green blocks with the embedded orange blocks evaluates to true, a value of 1 is set into and displayed by the variable identified by the statement immediately below the word if. Otherwise, a value of 0 is set into and displayed by that variable as shown in Figures 4 through 6.
An online version of this program is available
A copy of this program has been posted online for your review (see Resources for the URL). If you don't find the program using that URL, search the Scratch site for the user named dbal.
I encourage you to use the information provided above to write this program. Experiment with the code, making changes, and observing the results of your changes. Make certain that you can explain why your changes behave as they do.
Just for fun, see if you can create a startup screen that displays text similar to the title screen or the credits screen at a movie.
I also encourage you to write the programs described below.
Copies of these two programs have been posted online for your review (see Resources for the URL). If you don't find the program using that URL, search the Scratch site for the user named dbal.
Description: This Scratch program illustrates the use of relational and logical operators to determine if:
The following four variables are created, displayed on the Stage, and set to zero when the user clicks the green flag:
A button is also created and displayed on the Stage as shown in Figure 8.
Figure 8. Program output from the program named Logical02.
The value of each slider variable is set by the user moving the corresponding slider.
When the user clicks the button, if the left operand is less than or equal to the right operand, the third variable in the above list is set to 1. Otherwise, that variable is set to 0. If the left operand is greater than or equal to the right operand, the fourth variable in the list is set to 1. Otherwise it is set to 0.
Description: This Scratch program is a modification of the program named Logical02.sb. This is a relatively challenging program to write and requires an understanding of DeMorgan's theorem (see Resources).
The behavior of this program is identical to the behavior of the program named Logical02. However, it is likely that you used the or operator to write that program. This program does not use an or operator.
Instead, this program uses the not operator in conjunction with the and operator along with DeMorgan's theorem to produce behavior that is identical to the program named Logical02.
I provided an explanation of logical operators and truth tables. Then I presented and explained a Scratch program that illustrates the use of the logical and, or, and not operators when used in conjunction with relational operators.
Finally, I provided the specifications for two student-programming projects for you to demonstrate your understanding of what you learned from the first program and from earlier lessons. One of the student-programming projects is relatively difficult requiring an understanding of DeMorgan's theorem (see Resources).
Copies of all three programs have been posted online for your review (see Resources for the URL). If you don't find the program using that URL, search the Scratch site for the user named dbal.
Future lessons using the Scratch programming language will continue to deal with selection and will also deal with loops.
Copyright 2008, Richard G. Baldwin. Reproduction in whole or in part in any form or medium without express written permission from Richard Baldwin is prohibited.
Richard has participated in numerous consulting projects and he frequently provides onsite training at the high-tech companies located in and around Austin, Texas. He is the author of Baldwin's Programming Tutorials, which have gained a worldwide following among experienced and aspiring programmers. He has also published articles in JavaPro magazine.
In addition to his programming expertise, Richard has many years of practical experience in Digital Signal Processing (DSP). His first job after he earned his Bachelor's degree was doing DSP in the Seismic Research Department of Texas Instruments. (TI is still a world leader in DSP.) In the following years, he applied his programming and DSP expertise to other interesting areas including sonar and underwater acoustics.
Richard holds an MSEE degree from Southern Methodist University and has many years of experience in the application of computer technology to real-world problems.