Lesson 9: "if-else-if" and 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 in App Lab to practice using && and || in if statements. Finally, students will improve the Movie Bot so it can respond to multiple keywords and provide recommendations based on both the genre and rating provided by the user.

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.

Agenda

Getting Started

Activity

Wrap-up

Extended Learning

View on Code Studio

Objectives

Students will be able to:

  • Write and test conditional expressions using Boolean operators AND (&&) OR (||) and 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

Preparation

  • Decide whether to use Compound Conditionals worksheet. (Best to use after students have learned about if-else-if and Boolean Operators AND, OR and NOT).

    • Note: The first page of the worksheet should be distributed separately.
  • Review code studio levels and associated teacher's notes.

Links

Heads Up! Please make a copy of any documents you plan to share with students.

For the Teachers

For the Students

Vocabulary

  • Boolean - A single value of either TRUE or FALSE
  • Boolean Expression - in programming, an expression that evaluates to True or False.
  • Conditionals - Statements that only run when certain conditions are true.
  • If-Statement - The common programming structure that implements "conditional statements".
  • Selection - A generic term for a type of programming statement (usually an if-statement) that uses a Boolean condition to determine, or select, whether or not to run a certain block of statements.

Introduced Code

Teaching Guide

Getting Started

Review nested and chained conditionals

Goal: Review nested and chained conditionals and reveal their shortcomings when trying to express more complex logical statements.

Compound Conditionals worksheet - page 1

Teaching Tip

Reviewing Concepts: 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.

Pseudocode: 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: (Just page 1 of) (Optional) 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.

Discuss: 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.

Transition: 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.

Activity

Transition to Code Studio practice using && and ||

Transition to Code Studio:

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.

NOTE: If you want to break up the lesson into a few parts - the (Optional) Compound Conditionals - Worksheet contains many problems and activities that students can do on paper.

  • Using it is optional, but you might use it to reinforce concepts (or even introduce them if you like).
  • You don't have to use the whole thing. You may want to point students to individual pages for practice with certain things.
  • You could use and re-visit it at several points during this lesson as gathering-point activities.

Wrap-up

Review what makes logic tricky

Prompt:

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

  • 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.

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

  • 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*

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:

!(day=="Saturday" || 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 != "Saturday" && day != "Sunday") 

In other words: "It is the case that BOTH the day is not Saturday AND the day is also not Sunday."

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 && expr2 || 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.

Create PT Prep

If you have not already, complete and review the Create PT-style question that appears at the end of the lesson.

Preview "Building an App: Color Sleuth"

You've learned to write conditional statements and boolean expressions in a variety of ways on small programs so far. In the next lesson, you’ll have an opportunity to build an entire app from the ground up that will require to you write if statements and come up with your own conditional expressions.

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. Your processor 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.
  • Instruct student one to write a description of a real-life situation that requires multiple conditions.
  • When finished, the first student passes the description to the second student, 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 student, who writes code for the event. They may rely upon imaginary functions if necessary (e.g., is_raining())
  • Lesson Vocabulary & Resources
  • 1
  • (click tabs to see student view)
View on Code Studio

Teaching Tip

Answer Key:

Student Instructions

Unit 5: Lesson 9 - if-else-if and Conditional Logic

Background

Having explored the basics of simple if-else statements this lesson gets into how to express more complex logic using if-else-if statements and the Boolean operators && (and) and || (or). Again, you'll be presented with a number of small problems and scenarios to practice with and solve relatively more complex conditionals.

Vocabulary

  • Boolean - A single value of either TRUE or FALSE
  • Boolean Expression - in programming, an expression that evaluates to True or False.
  • Conditionals - Statements that only run under certain conditions.
  • If-Statement - The common programming structure that implements "conditional statements".
  • Selection - A generic term for a type of programming statement (usually an if-statement) that uses a Boolean condition to determine, or select, whether or not to run certain blocks of statements.

Lesson

  • How if-else-if works
  • How the Boolean operators && and || work
  • Compound Boolean Expressions

Resources

  • All in code studio
  • (Optional) Worksheet - Compound Conditionals (PDF | DOCX)

Continue

  • Introduction to Conditionals: if-else-if Statements
  • 2
  • (click tabs to see student view)
View on Code Studio

Student Instructions

Points to pay attention to:

  • An if-else-if statement lets you check more than one condition at a time.
  • The order of conditions matters. Since conditions are checked sequentially from top to bottom, the code that gets executed will be the first statement to evaluate to true.
View on Code Studio

Student Instructions

How if-else-if Works

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.
  • When you hit the + on the tail of an else clause it will add an else if into the statement.
  • 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.

A Worked Example

Here is an example that is similar to the one presented in the video. We've added an extra condition to illustrate how if-else-if statements work.

1. Ask the user to enter their age and save it in a variable.

2. First check to see if the age is 17 or over. If it is they can see an R-rated movie.

3. 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.

4. 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.

5. If we reach the final else clause it means all the previous conditions came up false. So this is what gets displayed.

6. Execution picks up on the first line after the if-else-if block. This "thank you" message at the end will display no matter what.

7. NOTE: because there is a final else clause you are guaranteeing that exactly one of these statements will execute. It is possible to write a chain of else-if conditions without a final else, in which case it's possible that the whole structure will be skipped.

What Can Go Wrong?

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

The order of the conditions matters!

  • An if-else-if will to execute the code for the first condition that comes up true -- all other conditions will be ignored.
  • An if-else-if statement is like saying, "FIRST check this condition, THEN check this one, THEN check this one and so on.

The common mistake is to accidentally have a condition early in the sequence that makes the other statements impossible to reach. For example, if you changed the order of the conditions in our movie ratings example:

1. This condition is true for any age over 4, so this console.log will execute right away, and the rest of the statements will be ignored.

2. Notice that it's impossible for either of these two conditions to even be reached. We can't check if the age is over 13 because it would have been caught by the first condition.

The misconception that leads to this mistake is to think that the if-else-if statement is considered in its entirety before execution - it's not. The conditions are checked sequentially, from top-to-bottom just like everything else.

Without a final else clause it's possible that the whole structure can be skipped

Just like an if statement without an else is skipped over if the condition is false, an if-else-if without a final else clause is skipped over entirely if none of the conditions is true.

Here is a generic example - forgetting what the code inside the if statements is supposed to do, just consider the if-else-if structure here.

What happens if val is 0? (or anything that's not 1, 2, 3, or 4?)

Answer: nothing. If val is 0 then each of the conditions will be checked in order, and since none of them is true, nothing will be executed.

This might seem obvious here, but the most common way this happens is that in your program you think that val can only be 1, 2, 3, or 4, but something happens to make it be some other value you weren't expecting. It's particularly hard to catch because there are no syntax errors here, nothing will crash due to an illegal operation. It will fail silently.

A way to protect yourself is to add a final else clause - even if you think it can't be reached - that prints a statement to yourself like "uh oh!".

Else-if is Convenient but Not Required (for AP)

It's worth noting that if-else-if doesn't provide you with any new capabilities that you didn't have before with plain old if-else statements. You can create any if-else-if structure by nesting if-statements.

Here is our movie ratings example with nested if-else statements - it functions exactly the same as if they were else-if statements as we described above.

It's so common to want to check multiple conditions that JavaScript (and most languages) have some notion of else-if built into the language. For example, if you wanted to check a set of 10 conditions, you wouldn't want to nest 10 if-else statements within each other. Nesting many statements can take up a lot of space with all the indenting. What you get with the if-else-if is basically a more nicely formatted, easier-to-read block of statements than its more primitive nested version.


NOTE: The AP Pseudocode DOES NOT Have else-if

It's also important to note that the AP pseudocode DOES NOT have else-if as a construct.

So on the AP exam if some problem requires checking multiple conditions you'll see it as nested if-else statements.

View on Code Studio

Student Instructions

if-else-if

Let's recreate the movie ratings example from the previous page (and video).

Add an if-else-if statement with a series of else-ifs to display the right message based on the user's age.

We've started you out with code that prompts the user for her age. We've also provided all the console.log statements you need.

Your task: Add an if-else-if statement with the appropriate Boolean expressions, and move the console.log statements into the right clause so the correct message gets displayed. Here is a reminder of what is supposed to happen.

  • If the user's age is 17 or over, they can see an R-rated movie
  • else if the user's age is 13 or over, they can see a PG-13 movie
  • else if the user's age is 5 or over they can see a PG movie
  • else display a message about the user being too young
  • Test out the program to make sure your updates worked.

Coding Tips

Create an else-if by hitting the at the bottom of an if statement. The first will add an else, the second will add an else-if.

Remove an else-if -- if you add an extra else-if by accident, you can remove it by switching into text mode and deleting the text. Don't forget to delete the curly-braces { and } that go with it.

View on Code Studio

Student Instructions

Quiz Grade

Prompt the user for their quiz score (0-100) and tell them what letter grade (A-F) they got.

Example: if the user enters 84 at the prompt your program should output: Your quiz grade is a B. Here's the score-to-grade breakdown:

Letter Grade:   A       B      C      D      F
 Score Range: 90-100  80-89  70-79  60-69  0-59

We've started you out with the prompt and the console.log statements you need. **Your task is to add the if-else-if statements to make it work.

Remember: the order in which you check the boolean conditions matters.

View on Code Studio

Student Instructions

Guess the Secret Number with else-if

In this guess-the-number game, the starting code tells the user whether they were right or wrong. Let's help the user out even more by telling them if they guessed correctly or if their guess was too high or too low.

There are only 3 possible cases:

  • They were right.
  • Their guess was higher than the number.
  • Their guess was lower than the number.

Use a conditional with and if, else-if, and a final else to implement this.

Remember: You can create an else-if statement by hitting the at the bottom of an if statement. The first will add an else, the second will add an else-if.

Do This:

  • Add an else-if statement to accommodate the 3 conditions.

  • Update the conditions using <, >, and == to tell the user if their guess was correct, high, or low.

  • Test out the program to make sure your updates worked.

Visual Explanation [Click to expand]

  • Sometimes it's helpful to see how the program should flow with a flow chart. The flow chart below depicts what should happen
  • View on Code Studio

    Student Instructions

    Debug Conditionals

    "Help! I was trying to give the player a hint when their guess was within 2 of the secret number but the code I wrote isn't working. Can you fix it?"

    This picture shows what the message should be based on the difference between the secret number and the player's guess:

    • Run the code to identify when the program is not working correctly (try guessing numbers 1-6)
    • Fix the problem with the order of the conditionals.

    Hint: The major problem here is that conditional statements run in order from top to bottom. Remember you have to check the smallest/most narrow case first, and work up from there. The conditions might be slightly non-intuitive at first glance. If you want to re-arrange the conditions it might be easier if you switch to text mode

    Check out the flow chart for the logic I wanted. [Click to Expand]

    Click image to open larger in a new tab

    • Introduction to Conditionals: Compound Boolean Expressions
    • 8
    • (click tabs to see student view)
    View on Code Studio

    Student Instructions

    Points to pay attention to:

    • The "Boolean operators" are AND and OR.
    • In JavaScript you write them as && for AND and || for OR.
    • You use them to combine boolean expressions into a single statement when you need to check multiple conditions before executing a particular segment of code.
    • How the Boolean &&, || and ! Operators Work
    • 9
    • 10
    • 11
    • (click tabs to see student view)
    View on Code Studio

    Student Instructions

    Boolean operators && and || and !

    The logical operators -- also known as the Boolean Operators -- AND (&&), OR (||) and NOT (!) allow you to compare the results of more than one Boolean operation at a time.

    NOTE: the OR is made with two vertical "pipe" characters. The "pipe" is on the keyboard with same button as \ -- it's right next to the key with }] on it, just above the Returnenter key.

    Example:

    The && operator (called "AND") lets you check whether two conditions are both true at the same time. Consider the statement below:

    This says: "True or false: is it the case that BOTH age >= 13 AND age < 21?"

    If both of expression 1 and expression 2 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.


    Breakdown: AND, OR and NOT


    Logical AND

    If both expr1 AND expr2 are true then the whole expression returns true.
    If either expr1 or expr2 is false then the whole expression returns false.


    Logical OR

    If either expr1 OR expr2 are true then the whole expression returns true.
    If both expr1 and expr2 are false then the whole expression returns false.


    Logical NOT

    This operator takes a single true/false value and inverts it. For example, maybe you want to say something like, "if it's NOT the case that age is less than 21" you could write this: !(age < 21). Even though that's logically the same as (age >= 21) sometimes it's clearer or more efficient to state something in the negative with NOT.


    Examples of Expressions with AND

    Here are two scenarios shown side-by-side that illustrate how a compound Boolean expression is evaluated step-by-step.

    The entire expression: age >= 13 && 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 or false.
    • Step 2 - evaluate the next expression in the statement (age < 21). It becomes true or false.
    • Step 3 - we can apply the rules of && to the values calculated in steps 1 and 2.

    Summary:

    • Scenarios 1 and 2 show how same expression evaluates differently depending on the starting value of age.
    • Each boolean expression is evaluated until it becomes a true/false value.
    • The logical operators work to return a single true/false value for the entire expression.



    Examples of Expressions with OR

    Here is an example for OR showing how the expression is evaluated step-by-step for two different scenarios.

    Misconceptions

    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"

    And then write this:

    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:

    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.

    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, apply the truth tables to make sure.

    Using an if statement

    Since compound boolean expressions eventually evaluate down to a single true/false value you 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:

    This shows how with one expression we can ask whether the person's age is between 13 and 22.

    Click continue to try it yourself

    View on Code Studio

    Student Instructions

    OR Operator

    You will now see the JavaScript boolean operators AND (&&) and OR (||) in code toolbox. You can drag them out or simply type them.

    Let's try OR right now. As a reminder: the OR operator will evaluate to true if either or both statements are true. If both are false, the OR operator will evaluate to false.

    Do This:

    We've provided you with starting code that prompts the user to enter a day of the week and stores it in a variable.

    Add the boolean expression to the if-statement to use an OR (||) to express:

    • IF it's Saturday or Sunday then write "It's the weekend!"
    • Else write "Can't wait for the weekend to get here."
    View on Code Studio

    Student Instructions

    AND Operator

    Again you will see the JavaScript boolean operators AND (&&) and OR (||) in code toolbox. You can drag them out or simply type them.

    Let's now try out using an AND operator. As a reminder: if both statements are true then AND evaluates to true. If either (or both) are false the AND operator will evaluate to false.

    Do This:

    We've provided you with starting code that prompts the user to enter their age and stores it in a variable.

    Add an if statement with a Boolean expression that uses an AND operator (&&) to express:

    • IF the age is between 13 and 19 write "You are a teenager."
    • ELSE write "You are not a teenager."
    • How Compound Boolean Expressions Work
    • 12
    • 13
    • 14
    • 15
    • (click tabs to see student view)
    View on Code Studio

    Student Instructions

    How Compound Boolean Expressions Work

    You learned before that for the Boolean operators &&, ||, and ! that you can plug in any expression that evaluates to true or false on either side of the operator.

    Of course, since compound boolean expressions evaluate to true or false, you 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.

    To prove the point, here's a completely made up long compound boolean expression with eight different other expressions. The block version gets particularly nasty-looking:

    With text we usually use parentheses to cluster expression so we know which should be evaluated together,

    (( expr1 || expr2 && expr3) && expr4) && (expr5 && expr6 || (expr7 || expr8))

    Now this is probably not a useful expression, but the point is that it could be evaluated assuming that expr1 through expr8 are Booleans.



    A worked example

    Let's look an example similar to the one in the video, and we'll breakdown process the computer goes through to evaluate this long expression step-by-step. In English what we're trying to express is:

    • "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:

    The scenario presented below shows how the expression is evaluated step-by-step to arrive at a single false at the very end. This particular scenario requires seven computations of Boolean expressions to whittle it down to the final single value.

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

    We could test this further with other values for day and age to verify we're getting the right results.

    Click Continue to try it yourself

    View on Code Studio

    Student Instructions

    Combining AND and OR

    You can express more complex conditions by combining AND and OR in one statement. Here is the example from the previous page which you can use as a reference. This statement will evaluate to true if the day is Tuesday or Thursday AND their age is 15 or 16.

    Do This:

    We've provided you with starting code that prompts the user to enter a day and their age and stores the result in variables.

    Add an if statement that uses both AND and OR operators

    • The app should write "Sleep in!" if it's a weekend and the user is a teenager.
    • Otherwise it should write "Uh oh. Have to wake up."

    Try it out!

    View on Code Studio

    Student Instructions

    You Try It

    Recreate the museum price example from the video.

    • We've setup everything for you except the boolean expression in the if statement is incomplete

    Modify the boolean expression (it just says age < 21 right now) to use combinations of && and || to reflect the following condition:

    • IF It's Tuesday or Thursday or the age is between 12 and 21 they get a discount
    • ELSE they pay full price

    TIP: switching to text mode might make this easier to compose.

    View on Code Studio

    Student Instructions

    Combining AND and OR and NOT

    You can stick a NOT (!) in front of any boolean expression to invert its result. This opens the door to express the same logical statements in different ways.

    For example, let's say you want to determine if a person, based on his or her age (under 12 or over 65) gets to pay a reduced price for a movie ticket. You might express that like this:

    // If your age is less than 12 or greater than 65
    if( (age < 12) || (age > 65) ){
        write("You qualify for a reduced price!");
    }
    

    But you might also figure out a way to determine if a person gets a reduced price ticket by determining if his or her age is between 12 and 65 ((age >= 12) && (age <= 65)) and then taking the inverse of that. So using the NOT operator this would work as well:

    // If your age is NOT between 12 and 65
    if( !( (age >= 12) && (age <= 65) ) ){
        write("You qualify for a reduced price!");
    }
    

    Why use one over the other? Personal preference. Use the one that makes the most sense to you, but it should be a clear expression of what you are trying to say.

    Do This:

    We've provided you with starting code that prompts the user to enter a day and their age and store it in variables.

    Add an if statement that uses both AND and OR operators

    • The app should write "Time for school!" if it's a weekday and the user is under 18.
      • Hint: one way to say that it's a weekday is to say that it's NOT a weekend.
    • Otherwise, if it's a weekday and the user is 18 or older, it should write "Time to go to work!"
    • Otherwise, it should write "Time to relax for the weekend!"

    WARNING logic can get tricky sometimes. Make sure to test your program with inputs that cover every possibility. There are 4 basic cases to test for:

    • It is a weekday and age is under 18
    • It is a weekday and age is not under 18
    • It's not a weekday and age is under 18
    • It's not a weekday and age is not under 18

    Try it out!

    • (new) AP Practice Response - Score the Response
    • 16
    • (click tabs to see student view)
    View on Code Studio

    Student Instructions

    AP Practice - Algorithm - 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)


    Here's the scoring guide for this question

    Score the 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."

    Program Code:

    Explain why you would or would not award the point for Row 5 based on the criteria given above

    Standards Alignment

    View full course alignment

    Computer Science Principles

    4.1 - Algorithms are precise sequences of instructions for processes that can be executed by a computer and are implemented using programming languages.
    4.1.1 - Develop an algorithm for implementation in a program. [P2]
    • 4.1.1C - Selection uses a Boolean condition to determine which of two parts of an algorithm is used.
    5.1 - Programs can be developed for creative expression, to satisfy personal curiosity, to create new knowledge, or to solve problems (to help people, organizations, or society).
    5.1.2 - Develop a correct program to solve problems. [P2]
    • 5.1.2J - A programmer designs, implements, tests, debugs, and maintains programs when solving problems.
    5.5 - Programming uses mathematical and logical concepts.
    5.5.1 - Employ appropriate mathematical and logical concepts in programming. [P1]
    • 5.5.1E - Logical concepts and Boolean algebra are fundamental to programming.
    • 5.5.1G - Intuitive and formal reasoning about program components using Boolean concepts helps in developing correct programs.