Skip to main content

Section 2.3 Selection

90 minutes
Up until now, we have been writing code one line at a time in sequence which then gets executed by the computer in that sequential order by default. However, we can create more complex algorithms that do not follow the default sequential order. The building blocks of algorithms are sequencing, selection, and repetition. In this lesson, we will learn to use selection to branch the code into different paths based on a condition. This allows us to create algorithms that can make decisions and respond to different situations.

Subsection 2.3.1 Selection in Algorithms

Essential Knowledge 2.3.1 2.3.A.1.

Some tasks require making a choice based on a condition. Selection allows an algorithm to choose different steps depending on whether a condition is true or false.
Selection is making a choice based on a true or false decision. For example, every time you login, the system checks your password and either grants access or denies it based on whether the password is correct.

Essential Knowledge 2.3.2 2.3.A.2.

Algorithms that use selection can be represented in ways people can read and follow, such as written steps or flowcharts.
In flowcharts, selection is represented by a diamond shape with a condition inside. The flowchart branches into different paths based on the outcome of the condition.

Activity 2.3.1.

Put the following steps of the algorithm in order.

Essential Knowledge 2.3.3 2.3.A.3.

Selection changes the path an algorithm follows. Different conditions can lead to different results because the algorithm may perform different steps based on the choice made.
This more complex flowchart for choosing a pet. Which path would you choose in this flowchart?

Subsection 2.3.2 Unplugged Activity: Simon Says Ifs

Project 2.3.2 Simon Says Ifs.

In groups or as a class or individually, play a game of Simon Says Ifs. One person will give commands using if statements and if-else statments. The players will follow the commands only if the condition is true or false for them. You do not have to say or listen for "Simon Says". Here are some examples:
  • If you are wearing blue, clap your hands.
  • If your first name starts with a "B", stomp your feet.
  • If you like cats, then meow, else bark.
Come up with your own 3 commands and write them below. Make sure they start with "if". At least one of them should also have an "else" part.

Subsection 2.3.3 Conditional Statements (If Statements)

Watch the following video about conditional statements using the words if and else.

Essential Knowledge 2.3.4 2.3.B.1.

Selection allows apps to respond differently depending on the information they receive. As a result, apps can handle user choices and provide helpful output instead of doing the same thing every time.

Essential Knowledge 2.3.5 2.3.B.2.

Programmers implement selection in code using conditional statements. Programmers use conditional statements to check a condition using a Boolean expression and run different code depending on the result.

Essential Knowledge 2.3.6 2.3.B.3.

An if-statement is a type of conditional statement used when a program needs to check a condition and take an action only when that condition is true. When the following code runs, the statements in block of statements are executed if condition evaluates to true. Otherwise, block of statements is skipped and the program continues.
if (condition)
{
   <block of statements>
}
Almost all programming languages have a keyword called if which is used to implement selection (also called conditional statements). If-statements are followed by a block of statements that are only executed if the condition is true. In languages like C, C++, Java, JavaScript, and the AP Pseudocode above, the block of code is marked by using curly braces {}. But Python uses colon (:) after the if condition and indentation to mark the block of statements under the if; the parentheses around the condition are optional in Python and usually left out. The syntax for a Python if-statement is below:
if condition:
   block of statements
The condition in an if-statement is any Boolean expression (like we learned in the last lesson) that evaluates to either true or false, for example number > 0. If you forget to indent the statements under the if statement, you will get an indentation error. Try it in the code below.

Activity 2.3.3.

The following code asks for your name and then prints out a greeting. Run the code twice and enter "Bart" the first time, and your name another time. The code prints different things depending on the input! Change the code to check against your name instead of "Bart" and run again.
Python also has a very useful operator called in that checks if a substring is inside a string. Try it in the code above instead of using "==" to check if part of your name is in the input string. For example,
if "B" in name:
    print("Welcome all names with B!")

Subsection 2.3.4 Relational Operators in If Statements

If statements can use relational operators to compare values. These operators which we saw in the last lesson are:
Do not confuse the equality operator (==) with the assignment operator (=). The equality operator checks if two values are equal, while the assignment operator assigns a value to a variable. If statements always use == to test a variable to see if it is equal to another value or expression.
If the variable in an if statement is a number that is user input, you must convert it to an integer or decimal (floating point number) using the int() or the float() function before you can use it in a comparison with relational operators, as seen below.

Activity 2.3.4.

The following code checks if an inputted number is positive. Add another if statement to check if the number is negative. Run the code twice to test it once with a positive number and once with a negative number.

Activity 2.3.5.

Given the code below, what will be printed?
x = 10
if x >= 10:
    print("A")
print("B")
  • A
  • Since 10 is greater than or equal to 10, A will be printed, but then the program continues running after the if statement, so more will be printed.
  • B
  • 10 is greater than or equal to 10
  • A and B
  • Correct. Since 10 is greater than or equal to 10, A will be printed, but then the program continues running after the if statement, so B will also be printed.
  • Nothing
  • x which is 10 is greater than or equal to 10.

Activity 2.3.6.

Given the code below, what will be printed?
x = 10
if x > 10:
    print("A")
  • A
  • 10 is not greater than 10
  • B
  • There is no print B statement in this code.
  • 10
  • No, x is not printed.
  • Nothing
  • Since 10 is not greater than 10, nothing will be printed.

Subsection 2.3.5 If-Else Statements

Essential Knowledge 2.3.7 2.3.B.4.

An if-else statement is a type of conditional statement used when a program needs to choose between two different actions based on whether a condition is true or false. When the following code runs, the statements in the first block of statements execute if the condition evaluates to true. Otherwise, the statements in the second block of statements execute.
if (condition)
{
   <first block of statements>
}
else
{
   <second block of statements>
}
If you want to choose between two actions, use an if-else statement. Although curly braces are used in some programming languages, in Python, the syntax for an if-else statement uses a : and indentation like below:
if condition:
   first block of statements
else:
   second block of statements
If the condition in an if-else statement is true, the first block of statements executes. If the condition is false, the second block of statements executes. In the activecode activity above, we wrote two if statements to check for positive and negative numbers, but we could have used an if-else statement to make the code more efficient.
if number > 0:
   print("The number is positive.")
else:
   print("The number is negative or 0.")

Activity 2.3.7.

The following program segment should ask whether the user wants to terminate the program and print out the appropriate statement based on the user’s response. The blocks have been mixed up and include extra blocks that aren’t needed in the solution. Drag the needed blocks from the left and put them in the correct order on the right. Make sure it is indented correctly!
Remember to use ==, not =, in the Boolean condition of an if statement to test a variable. One = assigns, two == tests!

Activity 2.3.8.

Change the following code so that the if condition checks against your favorite color (for example, "blue"). Add an else statement that prints out "That’s not my favorite color. My favorite color is ..." if the user enters a different color. Add another if/else statement to check if their favorite ice cream flavor is your favorite flavor (for example, "chocolate"). If it is, print out "That’s my favorite flavor too!", else print out "That’s not my favorite flavor. My favorite flavor is ..."

Essential Knowledge 2.3.8 2.3.B.5.

Choosing between an if and an if-else statement depends on whether the program should act only when a condition is true or should take one of two actions.

Essential Knowledge 2.3.9 2.3.B.6.

The result of conditional statements can be determined by evaluating the conditions and tracing which statements execute, including any changes to variable values or output.

Activity 2.3.9.

Given the code below, what will be printed if x = 9? In this code, mod (%) is used to check if a number is even or odd with the expression x % 2 == 0, because when even numbers are divided by 2, there is no remainder, but odd numbers always have a remainder when divided by 2.
x = 9
if x % 2 == 0:
    print("Even")
else:
    print("Odd")
  • Even
  • 9 divided by 2 has a remainder of 1, not 0.
  • Odd
  • 9 divided by 2 has a remainder so it is odd.
  • Even Odd
  • One or the other will be printed, not both.
  • Nothing
  • No, it will print Odd or Even.

Subsection 2.3.6 Logical Operators (and/or) in If Statements

To check multiple conditions in an if statement, you can use the logical operators and and or. Put complete tests using relational operators in each condition. With the and operator, both conditions must be true for the if statement to execute. With the or operator, at least one of the conditions must be true. The and operator is often used to check if a number is in a range, for example between 1 and 10 like below. The or operator can be used to check if a value is one of several possible values (for example uppercase or lowercase name like below) or error conditions like in the activity below.
if x >= 1 and x <= 10:
    print("x is between 1 and 10")
      
if name == "Ali" or name == "ali":
   print("Hello Ali!")

Activity 2.3.10.

Fix the indentation errors in the code below, and change it to use only one if statement using the or operator. The code should print "Error" if the number is less than 1 or greater than 10.

Essential Knowledge 2.3.10 2.3.B.7.

When multiple if-statements are written sequentially, each one is evaluated independently, so more than one block may execute if more than one condition is true.

Activity 2.3.11.

The following code checks a student’s grade and prints out the letter grade. Run it to see that it prints both A and C for a grade of 90! This is because the second if statement is not quite right because 90 is >= 90 and 90 is >= 70. Fix the if statement for the C grade so that it only prints C if the grade is >= 70 and < 80. Then add another if statement to check for a D grade (60- up to 70) and another if statement to check for an F grade (0- up to 60). Test your code by changing the grade and running it multiple times to test every if statement.

Subsection 2.3.7 Nested Conditional Statements

Essential Knowledge 2.3.11 2.3.C.1.

Apps often make layered decisions by checking a basic condition first and then checking a more specific condition. For example, an app might first check whether a user is logged in and then check whether the user has permission to access a feature. Nested conditionals allow programs to handle these multi-step checks.

Essential Knowledge 2.3.12 2.3.C.2.

A nested conditional is a conditional statement inside the block of another conditional statement. The inner conditional is evaluated only when the outer condition evaluates to true and execution reaches the inner conditional.
If statements can be nested inside other if statements forming nested conditionals. The inner if statement is only evaluated if the outer if statement’s condition is true. For example, the following code which could be written with nested if statements or an and logical operator. Notice that in Python, the nested if statement is indented within the block of the outer if statement to indicate that it is inside it.
# Nested if statements
if userLoggedIn:
    if userHasPermission:
        print("Access granted.")

# Or using an and logical operator
if userLoggedIn and userHasPermission:
    print("Access granted.")

Activity 2.3.12.

The following code figures out a ticket price for a movie according to the user’s age and the time at which the movie starts. Add a nested if statement to check for whether the movie is playing before 3 PM for a matinee discount. The movie theater opens at 1 PM, so don’t worry about AM hours. The variables age and hour have been set for testing, but you can comment out those lines to use your input too.
Nested if statements inside of else blocks can be used to make multi-way selections. A single if-else statement allows us to select between 2 branches of code. But with nested if-else-if statements, we can make multiple branches. Python has a shortcut keyword for this called elif which stands for "else if". Here’s an example of how it is used to chain together many conditions with the pattern if-elif-elif-...-else to branch the code into many directions. This is the same example of grade determination that we saw before, but this pattern of coding is shorter and easier to read. The extra tests for the maximum of each grade range is not needed because the tests are chained together. If the grade is not greater than or equal to 90, then it must be less than 90 when you reach the second test.
if grade >= 90:
    print("A")
elif grade >= 80:
    print("B")
elif grade >= 70:
    print("C")
elif grade >= 60:
    print("D")
else:
    print("F")
Here is a flowchart showing the if-elif-else multiple branching.

Activity 2.3.13.

Create code that sets the variable message to β€œHello” if x is less than 2, β€œHey” if x is greater than 2, and β€œHi” otherwise.

Essential Knowledge 2.3.13 2.3.C.3.

Nested conditional statements can be traced by evaluating each conditional statement’s Boolean expression in order, following the branch of code that runs, and keeping track of any updates to variable values or output that is produced.
Click on next to trace the execution of nested conditional statements.

Activity 2.3.14.

Keep clicking on the Next button at the bottom of the code to see how the values of the variables change as you step through the running program. You can see interactive tracing in any Active Code exercise by clicking the CodeLens button.

Activity 2.3.15.

What does the following code print when x has been set to 5 and y is set to -10?
if x > 0 and y > 0:
    print("positive")
elif x > 0 or y > 0:
    print("positive1")
else:
    print("negative1")
  • negative1
  • Not correct.
  • positive
  • This will only print positive if both x and y are positive.
  • Nothing
  • No, one of the conditions is true, so something will be printed.
  • positive1
  • Correct. Since x is positive, but y is negative, the or condition is true since at least 1 of them is positive, so positive1 will be printed.

Subsection 2.3.8 Adventure Coding Challenge

One of the first computer games was a text adventure game called Colossal Cave Adventure. You can try the adventure game recreated online following some of the commands in this walkthrough.
In this challenge, you can create your own text adventure game using if and elif statements. Your instructor may let you work in pairs. Where will your adventure take place? Will it be in a cave, a forest, a city, an island, a haunted house? You get to choose!

Project 2.3.16 Adventure Coding Challenge.

Create an adventure game with nested if-else statements. First, spend some time planning and designing your adventure locations. You may want to create a flowchart or other design documentation! Run the program below to see a template for your adventure game. Fill in the ...’s in the print statements and add more if statements for different choices in the adventure. Be careful with the nested indentation! Be creative!

Activity 2.3.17 Project Reflection on Algorithm.

Identify the first selection statement that you wrote on your own in your project. Explain how it works:
  1. What is the condition or Boolean expression being tested?
  2. When does the condition evaluate to true?
  3. When does it evaluate to false?
  4. What happens when if the condition is true?
  5. What happens when if it is false?

Activity 2.3.18 Project Reflection on Errors.

Describe a logic error (especially in the condition of the if statements) that you made or another programmer could make in your project code above. Describe the program behavior resulting from this error.

Activity 2.3.19 Project Reflection on Testing.

Explain how you tested your code with different inputs to make sure it worked correctly. If you have access to a Gen AI system, ask it what test cases it would recommend for your code and describe your prompt and its response.

Subsection 2.3.9 Learning Objectives Review

Learning Objective 2.3.14 2.3.A.

Represent an algorithm that includes selection using written steps or a flowchart.

Learning Objective 2.3.15 2.3.B.

Develop code using conditional statements, and determine the result of these statements.

Learning Objective 2.3.16 2.3.C.

Develop code using nested conditional statements, and determine the result of these statements.

Subsection 2.3.10 Vocabulary Review

Activity 2.3.20.

Subsection 2.3.11 App Inventor Project Continued (Optional)

If your class started the Lights Off app in MIT’s App Inventor, you can finish your app in section 2.14.4 Iteration 3 which uses if blocks and 2.14.5 Reflection in the App InventorLights Off App Lesson.
You have attempted of activities on this page.