Building Apps - Lesson 9: "if-elseif" and Compound Conditional Logic
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
Chained if-elseif statement: One "if-statement" structure that includes a series of leases inside.
Elimination logic: Often used in the "elseif" structure. The "if-conditional" or "else if-conditional" set earlier helps the succeeding "else if-conditionals" in eliminating some range of the conditions.
Compound Boolean Expressions: "if-conditional" or "elseif-conditional" that uses compound boolean operator "and," "or," and/or "not."
Nested if-statement: An "if-statement" (including chained elseif) that is inside of another "if-statement structure"
Goals
Students will be able to:
Write and test conditional expressions using Boolean operators AND (and) OR (or) and NOT (not)
Given an English description write compound conditional expressions to create desired program logic
Use a "chain" of if-else-if statements to implement desired program logic
When given starting code add if-else-if statements or compound boolean expression to express desired program logic
Introduced Code
if age < 13 or age > 65
if (day = "Tuesday" or day = "Thursday") or (age >= 13 and age < 21)
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.
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.
Is my partner's solution correct?
Is my partner's solution different from my own in any way?
Are there ways we could improve our solutions?
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.
You add an else-if clause to an if statement when you have another condition you want to check.
You can add as many else-ifs as you want.
Each condition in an if-else-if is checked in order from top to bottom and the final else clause is executed if all the previous conditions evaluated to false.
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:
Step 1: Ask the user to enter their age.
Step 2: Cast into an integer, the age that the user put in.
Step 3: First check to see if the age is 17 or over. If it is they can see an R-rated movie.
Step 4: If we reach this condition it means that the previous condition was false. So now let's check if the age is 13 or over and display a message.
Step 5: To reach this statement means that, so far, the previous conditions we've checked have come up false. So now let's check if the age is 5 or over and display a message.
Step 6: If we reach the final else clause it means all the previous conditions came up false. So this is what gets displayed.
Step 7: Execution picks up on the first line after the if-elseif block. This "thank you" message at the end will display no matter what.
What Can Go Wrong?
When writing if-elseif there are two common mistakes and thus two things to pay attention to:
The order of the conditions matters!
Without a final else clause it's possible that the whole structure can be skipped.
"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.
Pretend that you are the teacher who is programming this app for the students.
Your program needs to have the following functions:
A chance for a student to type in his/her score
An internal mechanism to determine the letter grade for the score(s)
Output the letter grade for the student.
As the teacher of the class, you have decided
to apply the following scale to determine the letter grade:
A is greater than 90%, B+ is 86% to 90%, B is 80% to 85%, C+ is 76% to 80%,
C is 70% to 75%, D+ is 66% to 70%, D is 60% to 65%, and F is less than 60%.
One of the easiest ways to write this
program is to use the "chained if-elseif statement". The following block
of code shows the pattern that you can follow to complete this code
(The code block only determines the A, B+ and B) for any score.
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
In this code example, we used the flow of
the code execution (top to bottom) to eliminate the need to
set the highest score for each letter grade.
Coding Challenge 36: Quiz Grade
Save this Project
Load a Project
Code Area
Output Area
"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:
The game will generate the random integer between 1 and 20 behind the scene.
The game will ask the user to guess "what number the computer came up with?"
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.
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.
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
Save this Project
Load a Project
Code Area
Output Area
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:
Output "The number is higher" when the user input the number smaller than the two numbers below the correct guess.
Output "Close! A little higher" when the user input the number smaller than the correct guess- yet within the two number value difference.
Output "The number is lower" when the user input the number larger than two number above the correct guess.
Output "Close! A little lower" when the user input the number larger than the correct guess - yet within the two number value difference.
Output "You win!" when the user input the correct integer.
As an example, let's assume the correct guess is 10. So your program should output:
Output "The number is higher" when the user input is less than 8.
Output "Close! A little higher" when the user input is larger than 7 and less than 10.
Output "The number is lower" when the user input is larger than 12.
Output "Close! A little lower" when the user input is larger than 10 and less than 13.
Output "You win!" when the user input 10.
Guess the Number
Save this Project
Load a Project
Code Area
Output Area
Elimination Logic
The following steps will explain how to "think" when constructing this "if-elseif statement":
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).
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).
We can apply the same thinking process for the userInteger that is higher than the computerInteger.
The only number that does not have any boolean condition above is the "correct" computerInteger.
The logical operators -- also known as the Boolean Operators -- AND (and), OR (or) and NOT (not) allow you to compare the results of more than one Boolean operation at a time.
Example:
The "and" operator (called "AND") lets you check whether two conditions are both true at the same time. Consider the statement below:
if age >= 13 and age < 21
This says: "True or false: is it the case that BOTH age >= 13 AND age < 21?"
If both of expression 1 (age >= 13) and expression 2 (age < 21) return true then the larger compound boolean expression returns true. You can replace expression 1 and expression 2 in that statement with anything that evaluates to true/false.
Truth Tables: AND, OR, and NOT
The "and" operator: (boolean expression 1)and(boolean expression 2)
(true) and (true) - returns true
(true) and (false) - returns false
(false) and (true) - returns false
(false) and (false) - returns false
The "or" operator: (boolean expression 1)or(boolean expression 2)
(true) or (true) - returns true
(true) or (false) - returns true
(false) or (true) - returns true
(false) or (false) - returns false
The "not" operator: not(boolean expression)
not (true) - returns false
not (false) - returns true
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:
Step 1 - evaluate the first expression encountered (age >= 13). It becomes true.
Step 2 - evaluate the next expression in the statement (age < 21). It becomes true.
Step 3 - we can apply the rules of "and" to the values calculated in steps 1 and 2. This entire expression returns true.
Example 2:
age = 25
(age >= 13) and (age < 21)
Step 1 - evaluate the first expression encountered (age >= 13). It becomes true.
Step 2 - evaluate the next expression in the statement (age < 21). It becomes false.
Step 3 - we can apply the rules of "and" to the values calculated in steps 1 and 2. This entire expression returns false.
OR operator
Example 1:
day = "Thursday"
(day = "Tuesday") or (day = "Thursday")
Step 1 - evaluate the first expression encountered (day = "Tuesday"). It becomes false.
Step 2 - evaluate the next expression in the statement (day = "Thursday"). It becomes true.
Step 3 - we can apply the rules of "and" to the values calculated in steps 1 and 2. This entire expression returns true.
Example 2:
day = "Wednesday"
(day = "Tuesday") or (day = "Thursday")
Step 1 - evaluate the first expression encountered (day = "Tuesday"). It becomes false.
Step 2 - evaluate the next expression in the statement (day = "Thursday"). It becomes false.
Step 3 - we can apply the rules of "and" to the values calculated in steps 1 and 2. This entire expression returns false.
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.
Incorrect
age < 13 and age > 65
Correct
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:
Step 1: day = "Tuesday" - returns false
Step 2: day = "Thursday" - returns false
Step 3: (day = "Tuesday" or day = "Thursday") - returns false
Step 4: age >= 13 - returns true
Step 5: age < 21 - returns false
Step 6: (age >= 13 and age < 21) - returns false
Step 7: (day = "Tuesday" or day = "Thursday") or (age >= 13 and age < 21) - returns false
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:
Let's assume that we have a museum that has the following policy for the admission price:
The museum is closed on Mondays.
Everyone gets half price discount on Tuesday and Thursdays.
If you are age between 13 and 20 (including min-max), you will get the discount on Wednesdays.
If you are younger than 6, or older than 65, your admission if free.
If you are age between 6 and 12 (including min-max), your admission is half price on the Weekend (Saturday and Sunday).
Build the program that gives the user to input the day of the week and his/her age, then gives the user information about the pricing for him/her. Your program should only have three patterns of output 1.) "We are closed on Monday," 2.) "You get half price discount!", 3.) "You pay full price."
Coding Challenge 38: Putting All Together
Save this Project
Load a Project
Code Area
Output Area
Activity: AP Practice Response - Score the Response
One component of the AP Create Performance Task is selecting and describing an algorithm that you developed.
2. Written Responses
2c. Capture and paste a program code segment that implements an algorithm (marked with an oval in section 3 below) and that is fundamental for your program to achieve its intended purpose. This code segment must be an algorithm you developed individually on your own, must include two or more algorithms, and must integrate mathematical and/or logical concepts. Describe how each algorithm within your selected algorithm functions independently, as well as in combination with others, to form a new algorithm that helps to achieve the intended purpose of the program. (Must not exceed 200 words)
The scoring guide for this question is shown in the picture.
Now, score the following response:
Written Response: 'My algorithm controls the log-in for the app. This piece of my program is important because the data included in my app needs to be secure. The algorithm makes sure only users with the correct password get in to the app to use it.'
The program code is as follows:
Wrap Up
"What's the trickiest logical statement you encountered in this lesson? What made it tricky?"
Ideas to discuss with the students:
We often use "and" and "or" in English in imprecise ways, or at least in ways that could have multiple meanings. In programming logic, AND and OR have very precise meanings and they don't always map directly to English.
An example using OR
In English, we sometimes use OR in the same way it's used in programming - to mean either or both. "Do you want cream or sugar in your coffee?" But we often use OR to mean exactly one thing or the other, not both. "Is the elevator going up or down?" The programming-logic answer to that question is: yes. Because it is the case that the elevator is either going up or it's going down.
AND can get really tricky because in English we sometimes use the word "or" to convey a logical AND. For example: In English you might say: "If it's not Saturday or Sunday, then it's a weekday." In programming you might express this as:
not(day = "Saturday" or day = "Sunday")
In other words: "It is not the case that the day is Saturday or Sunday." But you might also express the same condition in code as:
(day not= "Saturday" and day not= "Sunday")
In other words: "It is the case that BOTH the day is not Saturday AND the day is also not Sunday."
Prompt:
"True or False: the Boolean operators AND, OR and NOT, enable us to express boolean conditions that we couldn't before?"
Ideas to discuss with the students:
False. Anything that you can express with AND, OR and NOT, can be expressed with a chain or nesting of if-else statements. Certainly, it allows us to expression complex boolean conditions more succinctly, and makes our code MUCH easier to read. But in terms of program logic, we can do everything with just if-else statements.
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.
AND gate: Two wires are attached to one side of an AND gate, and one is attached to the other. If both input wires have a high voltage, the AND gate will give a high voltage to the output wire.
OR gate: Two wires are attached to one side of an OR gate, and one is attached to the other. If either input wire has a high voltage, the OR gate will give a high voltage to the output wire.
NOT gate: One wire is attached to one side of a NOT gate, and one is attached to the other. If the input wire has a high voltage, the output wire will have a low voltage and vice versa.
Collaborative programming
Form teams of three students.
Assign one to write a description of a real-life situation that requires multiple conditions.
When finished, the first person passes the description to the second person, who is tasked with drawing the flowchart or pseudocode for the scenario.
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())