Hour 9: Conditionals

This lesson is to introduce you to conditionals.

Overview

So far, you have made programs that are sequential, meaning they always follow the same set of instructions from start to finish. In practice, programs are rarely so linear. Often, you need to do different things depending on data that a computer program has available. In this lesson, you will learn how to use conditional statements to change what code you run.

Goals

You have the following goals for this lesson:

  • Learn how to use if statements to control program execution
  • Learn how to further control code with else and elseif blocks
  • Learn how scope affects variables created inside “if” statements

Warm up

Traveling somewhere new can be fun, but requires planning. When you plan for a vacation or other travel, what are some factors that you consider when you start to pack your suitcase? How do you decide what to bring? Now, consider your decision making process. Can you formalize your decision making into rules (e.g. if X, then I will bring Y)?

Vocabulary

You will be learning about the following vocabulary words:

Vocabulary
TermDefinition
Conditional StatementA statement in computer science (typically an if statement) that will only run when the condition is true.
Boolean ExpressionAn expression in programming that evaluates to either true or false.
ConditionalAn expression a program will check if true or false before proceeding to an action

Code

You will be using the following new pieces of code:

New Code to Learn
Quorum CodeCodeExplanation
if (condition) endif true endThe if statement is a conditional statement. If the program evaluates the condition to be true, it will run the block of code contained inside.
elseifif false elseif true endThe elseif block is a conditional that is only checked if the previous conditions in the structure were false. If the previous conditions were false and the elseif’s condition is true, it will execute the code contained within the elseif.
elseif false elseif false else endThis is the default case in a chained if statement. This code will always run if all another above if statements evaluate to false

CSTA Standards

This lesson covers the following standards:

  • 1B-AP-10: Create programs that include sequences, events, loops, and conditionals.
  • 2-AP-11: Create clearly named variables that represent different data types and perform operations on their values.
  • 2AP-12: Design and iteratively develop programs that combine control structures, including nested loops and compound conditionals.
  • 3A-AP-15: Justify the selection of specific control structures when tradeoffs involve implementation, readability, and program performance, and explain the benefits and drawbacks of choices made.

Explore

You use if statements to teach the computer to make decisions on its own. Some might call this artificial intelligence (AI). This is sort of true in the sense that the computer can learn to make decisions all on its own. However, this form of artificial intelligence is primitive and not usually what an expert would mean when they say AI. At the end of the day, an if statement decides whether or not to execute another piece of code.

Imagine that you are playing a video game. For example, perhaps you are facing an enemy and you have two decisions of what your next move would be: fight or flight. You could formalize your decision making process with some rules. It might look something like this:

if creature = "monster"
     output "run away!"
end

Using this rule would assume you have a variable somewhere named creature and that it is text. If that text happens to have the name monster, run away. Just like you can formalize rules for your decision making, you can also make rules for the computer to follow. If statements allow you to control what code the computer executes depending on the rules or conditions you set.

There are 3 major parts of a conditional, the

  • if statement (plus conditional),
  • Zero or more elseif statements (plus conditional), and then an
  • optional else statement.

Creating a Conditional Statement

Creating a conditional statement involves using the if structure to teach the computer to only react sometimes. In computer science, although many languages are very similar for this feature, the code for conditional statements does vary between languages. In Quorum, the code is as so:

if conditional
   // perform action A
else
  // perform action B
end

When you think about how to write a conditional, it is often broken down into decision making where event A happens if the condition is true and event B happens if the condition is false.

A flow chart format asking the question: Is it raining
If true, then you play indoors
If false, then you play outside

The condition must be a boolean expression with only the values true or false. These conditionals again use any or all of the following boolean operators:

Equalities and Inequalities
Operator NameOperatorExplanation
Equality=Checks if two values are equal.
Inequalitynot=Checks if two values are not equal.
Greater than>Checks if one value is greater than another.
Less than<Checks if one value is less than another.
Greater than or equal to>=Checks if one value is greater than or equal to another.
Less than or equal to<=Checks if one value is less than or equal to another.

Additionally, there are logical operators that are often used with conditional operators to combine multiple conditions:

Logical And, Or, and Not
Operator NameOperatorExplanation
Logical andandTrue if both conditions are true
Logical ororTrue if at least one of the conditions is true
Logical notnotInverts the truth value of a condition

Notice that these match exactly with the kinds of operations taught in the Parsons problems for booleans. You can use different types of variables with these conditional operators. For example: 5 < 10 would result in true and 4 < 10 and 7 >= 15 would result in false.

Nested Conditionals and elseif

It is possible (and sometimes useful) to place conditionals inside of other conditionals. Be careful when nesting them. Doing so is commonplace in programming, but some discretion to keep your code from getting confusing is warranted. Here is an example from grading, written as text in part because examples of this size tend to get hard in an alternative description:

integer testScore = 75
text grade = ""
if testScore > 90
	grade = "A"
else
	if testScore > 80
    		grade = "B"
	else
    		if testScore > 70
        			grade = "C"
    		else
        			grade = "D"
    		end
	end
end
output "Student's grade: " + grade

If statements can be tricky to grasp and easy to mess up. For example, with the previous example you have to think more carefully about what is going on in this piece of code because the testScores are nested. Thus:

  • If the testScore is greater than 90, it gets an A.
  • Otherwise, it checks if the score is greater than 80 for a B.
  • If not, it looks at scores above 70 for a C.
  • Finally, anything below 70 gets a D.

As a reminder, each if statement is nested, meaning inside of, the scope of others. Because of this, not all aspects of this code ever run. In terms of obtaining information about it, scoping can be determined multimodally. Visually, some multi-line blocks are inside of each other and shoved to the right. This means they are self-contained in that region. Aurally, for screen reader users, although screen readers vary slightly in what they read, they tend to say first the line of code, in addition to the nesting level and the number of top level blocks inside that region. The idea is that you can get a sense of scope in different ways.

In this particular case, instead of nesting conditionals, you can use the elseif block to test extra conditions. Examine the revised example below:

integer testScore = 75
text grade = ""
if testScore > 90
	grade = "A"
elseif testScore > 80
	grade = "B"
elseif testScore > 70
	grade = "C"
else
	grade = "D"
end
output "Student's grade: " + grade

Lines that start with elseif statements are optional extra pieces you can add to an if statement. They act as extra conditionals that are only tested if the conditions before them were false. Conditions are always evaluated in order, from top to bottom, and the if statement will never check or run other conditionals or their code if a previous condition was true. Both approaches are used commonly and which one to use in your own code can be situational. Nested code is arguably harder to understand, but sometimes you might need that flexibility.

Nothing else worked, so else

As one final block, you can add an else block to an if statement. In text, this might be as follows:

if condition
	//do something
elseif condition2
	//do a different something
elseif condition3
	//do an even more different something
else
 	//condition, condition2, and condition3 were all false
end

The basic idea is that the computer checks the condition in the if first. If it is true, the block executes and then jumps to the final end. If it is false, it then checks condition 2, with the same procedure. The idea is that one, and only one, of the blocks runs.

Engage

Conditionals are also an extremely important skill to learn in computer science. In day to day use as a programmer, they are one of the most common pieces of code you will write. For these Parsons problems, you will practice understanding and using conditionals.

Given that conditionals make heavy use of boolean variables and operators, if you forget the concepts, consider jumping back to those lessons or redoing the Parsons problems as practice before doing this one.

Directions

You will now continue using Parsons problems. This time, you will practice using conditionals in a variety of ways. This includes using if, elseif, else, and also practicing boolean expressions. If you forget the details of boolean operations, you may want to consider going back and practicing those operations one more time. Part of the purpose in combining if with continued practice with boolean expressions is because the concept is so commonplace, and so fundamental, to programming, that practicing regularly with new examples can be helpful. These examples are in the context of conditionals, but the same applies.

As before with these Parsons problems, you can drag and drop, use the keyboard, or even just write in the editor the solution to the problem and run the code. As a reminder, the hotkey to run the code is ALT + SHIFT + R on Windows and CTRL + SHIFT + R on Mac.

  1. Learn about if

Wrap up

The flavor of the month in computer science is often termed AI and the media often conflates seemingly any software that has been invented with it. What do you think the differences are between what a computer scientist might mean for AI and an if statement?

Next Tutorial

In the next tutorial, we will discuss Traversals Online, which describes how to work with traversals.