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

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.
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.
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, 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.
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!")

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.4 If-Else 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 ..."

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.

Activity 2.3.10.

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.5 Nested Conditional Statements

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

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

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.
Click on next to trace the execution of nested conditional statements.

Activity 2.3.13.

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

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.6 Adventure Coding Challenge

Project 2.3.15.

Create an adventure game with nested if-else statements. You could work in pairs! First, spend some time planning and designing your adventure locations. You may want to create a flowchart or other design documentation! 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.16. 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.17. 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.18. 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.7 Vocabulary Review

Activity 2.3.19.

Subsection 2.3.8 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.