Overview

In this lesson, students will be introduced to the boolean (logic) operators NOT, AND, and OR as tools for creating compound boolean conditions in if statements. Students will learn how to more efficiently express complex logic using AND and OR, rather than deeply nested or chained conditionals. Students will work through a worksheet that covers the basics and a few problems with evaluating logical expressions, then write code to practice using AND and OR in if statements.


Vocabulary

Goals

Students will be able to:

Introduced Code

Purpose

Similar to the previous lesson, the primary objective here is practice, practice, practice! We want students to get into the exercises and solve many different types of problems in many different types of contexts so they can pick up the patterns of writing, testing and debugging if-statements with more complex conditions.

This lesson introduces both the if-else-if construct and the Boolean operators AND, OR, and NOT. While it may appear that these operators extend the types of boolean conditions we can write, this is not actually the case. Nested and chained conditionals alone can be used to express any possible set of boolean conditions. The addition of these new boolean operators merely helps that expression be more succinct, clear, and elegant. But logic can get tricky, since often the way we say things in English is not the way we need to write them in code.

Resources

Getting Started

This warm-up activity is an excellent opportunity to review nested and chained conditionals. You may wish to briefly remind students what each of these is prior to the warm-up activity. Students should verify that one another's solutions are valid and make proper use of chained and nested conditionals.

Students will be writing their solutions in pseudocode, which is a useful and important skill. Highlight that their syntax need not be perfect but that their pseudocode should be clear and reflect the actual programming structures they have seen.

Distribute the first page of "Compound Conditionals Worksheet" and ask students to work together on the questions on the first sheet. Hold off on distributing the rest of the worksheet, since it shows an example solution to each of the problems from the first page.

Have students share their answers with their neighbors and compare to see if they had the same solutions. Students can use the following questions to drive their conversations.

You may wish to demonstrate possible solutions to each question, but they will also be found later on in that same worksheet.

Activity

Nested and chained conditionals are important tools when designing boolean conditions in our programs. In fact, every boolean condition can be expressed in some way using nesting and chained conditionals. That said, often when we write out these solutions they are long or force us to write redundant code. Today were are going to learn some new tools that won't let us write any new conditions, but WILL allow us to write many complex conditions much more clearly.

Much like the previous lesson, students will complete a series of short exercises to write code into "toy" programs to get practice using if-else-if constructs and the logical operators AND, OR, and NOT.

Activity 1: Chained if-elseif statement

Not all conditions you want to check have only two possible outcomes. However a computer can only check one true/false condition at a time.

How It Works

As an example, the code is as follows

text textAge = input("How old are you?")               //Step 1
integer intAge = cast(integer, textAge)                //Step 2

   if intAge >= 17                                     //Step 3
       output "You can see an R movie alone."      
   elseif intAge >= 13                                 //Step 4
       output "You can see a PG-13 movie alone."       
   elseif intAge >= 5                                  //Step 5
       output "You can see a G or PG movie alone."     
   else                                                //Step 6
       output "Uh. You're too young for most things."
   end

output "Thanks for verifying your age!"                //Step 7

The corresponding steps are:

What Can Go Wrong?

When writing if-elseif there are two common mistakes and thus two things to pay attention to:

"Quiz Grade" Challenge

This challenge will reinforce the idea of if-elseif statements by building a console app that determines the letter grade of a student based on the percentage of the quiz score that the student receives. Let's say a student takes a quiz and receives a numeric percentage of the score (100% being a perfect score). The student needs to type in his/her score in this app to find out what letter grade he/she receives.





text userScore = input("Enter you quiz score.")
integer intScore = cast(integer, userScore)

   if intScore > 90
       output "A"
   elseif intScore >= 86
       output "B+"
   elseif intScore >= 80
       output "B"
   end

Coding Challenge 36: Quiz Grade

"Guess the Secret Number" Challenge

This is a new game that asks the user to guess a number.

The game runs in the following order:

  1. The game will generate the random integer between 1 and 20 behind the scene.
  2. The game will ask the user to guess "what number the computer came up with?"
  3. The game also tells the user that he/she has only 5 times to guess. If the user can get the right number within the 5 trials, the user wins. If the user does not, the computer wins.
  4. Every time the user input the guessed number (which may or may not be correct), the computer will give the user the hints. this part will be explained in detail in the next section.
  5. The computer will give the user the 5 trials regardless of the user wins or not. Consequently, if the user keeps playing the game after wining, the game will tell the user he/she lost the game at the end. (This is due to the limitation of knowledge we have so far about "repeat syntax"). The goal for the user is to win the game within this 5 trials.

use Libraries.Compute.Random
Random ran
integer computerInteger = ran:RandomIntegerBetween(1, 20)

text welcomeScreen = input("welcome to the number guessing game. I have just came up with one number between 1 and 20. Can you guess what the number is? You have 5 chances to guess. Press [enter] to continue.")

integer counter = 0

repeat 6 times
   if counter < 5
       text userInput = input("Type your guess and press [enter]")
       integer userInteger = cast(integer, userInput)

       counter = counter + 1
   else
       output "You lost the game. The number was " + computerInteger
   end
end

Copy and paste the code above into the IDE below. Run the code and see if you understand what is going on

Guess the Number Template

Finishing Up the "Guess the Secret Number" Challenge

Your program needs to give the user the hints when he/she input the incorrect guess - based on how much off the target the user's guess is. There should be four patterns of hints. Your program gives the user the hints:


As an example, let's assume the correct guess is 10. So your program should output:

Guess the Number

Elimination Logic

The numberline extends to infinity to the positive and negative. There are three points idicated. The center point is at 0. This indicates the origine of the computer generated number. To the left of the center point is the point with -2. To the right of the center point is the point with +2.

The following steps will explain how to "think" when constructing this "if-elseif statement":

  1. Write an "if statement" that eliminate the possibility the userInteger being lower number than the (computerInteger - 2). This will eliminate the possibility of any number below (computerInteger - 2).
  2. In the "elseif" statement, we can just check if the userInteger is less than the computerInteger because we already eliminated the condition of the userInteger smaller than (computerInteger - 2) in the first "if statement" line, so this "elseif statement" is actually evaluating if the userInteger would fall into between the computerInteger and (computerInteger - 2).
  3. We can apply the same thinking process for the userInteger that is higher than the computerInteger.
  4. The only number that does not have any boolean condition above is the "correct" computerInteger.

Activity 2: AND and OR Operators


Boolean operators "and," "or," and "not"



     if age >= 13 and age < 21


Truth Tables: AND, OR, and NOT

The "and" operator: (boolean expression 1) and (boolean expression 2)

The "or" operator: (boolean expression 1) or (boolean expression 2)

The "not" operator: not (boolean expression)

AND operator

Example 1:

age = 17
(age >= 13) and (age < 21)

The entire expression: "age >= 13 and age < 21" will end up as a single true/false value depending on what the value of age is. But it's computed one step at a time. This expression has 3 steps to it:

Example 2:

age = 25
(age >= 13) and (age < 21)


OR operator

Example 1:

day = "Thursday"
(day = "Tuesday") or (day = "Thursday")

Example 2:

day = "Wednesday"
(day = "Tuesday") or (day = "Thursday")

Misconceptions

Here are some of the common problems that you might encounter.

Syntax Problems

It's common to forget that you need to state a full Boolean expression on each side of the logical operator. This happens because of the way we state conditions in English. For example in speaking English you might say:

"If the day is Saturday or Sunday"

day = "Saturday" or "Sunday"

This is incorrect because "Sunday" by itself is not a boolean expression - it isn't true or false. So the correct version is a bit more verbose but one the computer can process:

day = "Saturday" or day = "Sunday"

Just remember that each side of a boolean operator needs to evaluate to true or false.

Logic Problems

There are logical misconceptions because the way we use "and" and "or" when speaking in English which is sometimes ambiguous. Take these two statements which if you heard them in regular English mean the same thing:

"Patrons under the age of 12 and over the age of 65 get a discount"

"Patrons who are under 12 or over 65 get a discount"

One statement uses and and the other one or. If you're writing code, which should it be? Does it matter? It turns out: yes.

       age < 13 and age > 65
       age < 13 or age > 65

The expression with AND is incorrect because the logical AND means that both of these expressions must evaluate to true at the same time for the whole statement to be true. In fact, there is no value of age that will make this statement true! -- a person cannot be both under 13 and over 65 at the same time. The correct expression is the one with OR because we want one of two things to be true: either the age is under 13 OR the age is over 65. This example shows that English may mislead you if you're not careful. So after you write an expression, clear your mind, imagine that you are a dumb logical computer and test it by applying the truth tables to make sure.

Using the compound expression in "if-statement"

Since compound boolean expressions eventually evaluate down to a single true/false value, we can use them in an if statement. The whole expression evaluates to determine whether or not execute a section of code. Here is a simple example for the students to read through:

text userAge = input("How old are you?")
integer userInteger = cast(integer, userAge)

if age < 13 or age > 65
   output "You get a discount"
else
   output "Sorry, NO discount"
end

Activity 3: How Compound Boolean Expressions Work

Concept: Since compound boolean expressions evaluate to true or false, we can also use compound boolean expressions within other compound boolean expressions to make an even more sophisticated statement. In fact, there is no limit to how many boolean expressions you can embed within a single statement. For example:

((expr1 or (expr2 and expr3)) and expr4) and ((expr5 and expr6) or (expr7 or expr8))

** Note: We usually use parentheses to cluster expression so we know which should be evaluated together.

An Example to Work Through With Students

In English, we are trying to express:

"If it's a Tuesday or a Thursday, or the person is between the ages of 13 and 21 (including 13 but not 21), then they should get a discount."

Here is the entire compound boolean expression in an if-statement:

if (day = "Tuesday" or day = "Thursday") or (age >= 13 and age < 21)
   output "You get a discount!"
else
   output "You pay full price."
end

Walk through the code when day = "Wednesday," age = 21. When the user input these data, the computer goes through the step by step boolean evaluation in the following order:

This is the correct result. Since it was a Wednesday, it wasn't the right day for a discount. And because the user was 21, but our statement says you have to be under 21, they also don't qualify on age.

Museum Price Challenge

The problem statement is as follows:


Coding Challenge 38: Putting All Together

Activity: AP Practice Response - Score the Response

One component of the AP Create Performance Task is selecting and describing an algorithm that you developed.

The scoring guide for this question is shown in the picture.

AP Scoring Guide

Now, score the following response:

The program code is as follows:

Program Code

Wrap Up

"What's the trickiest logical statement you encountered in this lesson? What made it tricky?"



       not(day = "Saturday" or day = "Sunday")

       (day not= "Saturday" and day not= "Sunday")

Prompt:

"True or False: the Boolean operators AND, OR and NOT, enable us to express boolean conditions that we couldn't before?"

Logic can get tricky

Because logic can get convoluted and tricky, even professionals mess it up. However, as a programmer, you can take steps to make sure you"ve got it right by testing your code thoroughly to make sure you get expected results.

Because the boolean operators essentially take binary values (T/F) as input, you can easily figure out how many possible inputs there are for any complex boolean expression and test them all. For example if you have a statement like:

if (expr1 and expr2 or expr3)

There are 3 expressions there, and each can be either true or false, so there are 8 possible ways to assign true or false to expr1, expr2 and expr3 -- (TTT, TTF, TFT, TFF, FTT, FTF, FFT, FFF). You can test all 8 to make sure you get the right outputs.

Extended Learning

Connection to logic gates in hardware: These AND, OR, and NOT logic operators can be very useful in directing the flow of your programs. They also represent a fundamental part of your computer's hardware. Computer engineers uses logic gates such as these to do computations and direct the flow of information. Remember, inside your computer, you have electricity flowing; "true" is indicated by a high voltage and "false" is indicated by a low voltage.

Collaborative programming

  1. Form teams of three students.
  2. Assign one to write a description of a real-life situation that requires multiple conditions.
  3. When finished, the first person passes the description to the second person, who is tasked with drawing the flowchart or pseudocode for the scenario.
  4. The paper with the description and flowchart or pseudocode is then passed to a third person, who writes code for the event. They may rely upon imaginary functions if necessary (e.g., is_raining())

Standards Alignment