6 Conditionals and Making Choices
6.1 if
Statements
Many times in programming, we want to take a certain action only if a certain condition is satisfied.
To do this, we can use conditional statements. The most commonly used format of a conditional statement in programming is an if
statement, which is often combined with an else
statement.
This structure tells the computer to check a condition and the next step depends on whether the condition is true or false.
It takes the basic form of:
IF (condition A is TRUE)
do something
In terms of our cheesy mashed potatoes algorithm, an if
statement might look like this
ingredient <- cheddar cheese
IF (ingredient is (a type of hard cheese))
grate(ingredient)
In that example, we’ve told the computer what to do if the condition is true. We can also specify what to do if the condition is false.
For our cheesy mashed potatoes algorithm, we may want to cut cheese into cubes if it is not a hard cheese:
ingredient <- cheddar cheese
IF (ingredient is (a type of hard cheese))
grate(ingredient)
ELSE
cube(ingredient)
In pseudocode, a complete if else
statement would look like:
IF (condition A is TRUE)
do something
ELSE
do something different
Here, else
is used equivalent to “if not true”, meaning A == FALSE
.
Furthermore, we are not limited to a single TRUE
/FALSE
check in an if else
statement, where actions are limited to “do something if true, in all other scenarios do something different”. The else if
(written as elif
in some programming languages) concept allows us to add another sequential check if the if
statement is not true.
An updated cheesy mashed potato narrative statement could be that if we have a hard cheese, we want to grate it, if we have a soft cheese we want to cube it, and if we have something that is neither hard nor soft cheese, we don’t put it in the potatoes.
IF (ingredient is (a type of hard cheese))
grate(ingredient)
ELSE IF (ingredient is (a type of soft cheese))
cube(ingredient)
ELSE
don't use
In pseudocode, this updated statement would look like:
IF (condition A is TRUE)
do something
ELSE IF (condition B is true)
do something different
ELSE
do something even more different
6.2 Exercise - Popcorn if else
pseudocode
Timing: 5 minutes
Let’s try a similar example with the popcorn algorithm from section 2.
Write out an if else
statement specifying what appliance to use in the case of
different popcorn types: bagged popcorn (bagged
), popcorn in an aluminum pan (jiffy_pop
),
and loose kernels.
Then, write out an if, else if, else
statement that includes use of an air fryer for loose kernels.
Example statement
IF (popcorn_type is `bagged`)
use microwave
ELSE (popcorn_type is `jiffy_pop`)
use stove
IF (popcorn_type is `bagged`)
use microwave
ELSE IF (popcorn_type is `jiffy_pop`)
use stove
ELSE
use air_fryer
Your version may look different, and that’s fine! The fun of pseudocode is practicing with the logic of code, rather than getting lost in the details.
6.3 Comparing Things and Booleans
In programming, most things boil down to true
or false
. (Sometimes you may see true/false capitalized as TRUE
and FALSE
, but the concept is the same. We’ll use both ways throughout.). TRUE
and FALSE
are formally a boolean data type. Programming languages use boolean operators and comparison operators to determine if a statement is TRUE
or FALSE
in order to make actions.
Common Boolean operators are:
-
and
(may also see the ampersand,&
or&&
used) -
or
(may also see the pipe symbol,|
or||
used) -
not
(may also see!
to indicate negation, for instance!=
for “not equal”)
Common comparison operators are:
-
>
Greater-than -
<
Less-than -
>=
Greater-than or equal-to -
<=
Less-than or equal-to -
==
is equal to- you should note that
==
is very different from=
.==
is the comparison operator, while=
is an assignment operator. Another assignment operator you may have noticed us using is<-
which is commonly used in R. - To practice, you can replace the words “is equal to” or “is assigned the value of” appropriately.
-
A = 6
(A
is assigned the value of6
) -
B <- 8
(B
is assigned the value of8
) -
B == 7
(“B
is equal to7
”, where the statement is then evaluated to betrue
orfalse
. In this case, it isfalse
)
- you should note that
6.4 Conditional Statements in Practice
Let’s look at some examples of conditional statements in practice, first by using our cheesy mashed potatoes example, and then with actual code.
First, for our recipe example:
if cheese == hard:
print("Grate the cheese.")
else if cheese == hard:
print("Cube the cheese.")
else:
print("Do not use this in this recipe.")
If we have cheese <- parmesan
we would expect this statement to print out Grate the cheese
. If we have cheese <- brie
we would expect the output to be Cube the cheese
. And if we have cheese <- broccoli
we would expect the output to be Do not use this in the recipe
.
Sidenote: yes, this assumes that somewhere we have specified a list of hard cheese and soft cheeses. For this pseudocode example, we’re using our cheese-based expertise to draw conclusions, but as we’ve covered, we would never assume a computer would know which cheeses were hard or soft!
6.4.1 Exercise: ifelse
Trace
Timing: 5 minutes
For this exercise, want you to type the answer in the chat, but don’t press enter until we tell you. We’ll say, 3, 2, 1, enter then you press enter when we say enter.
For the code below, what will be the printed output?
x <- 37
y <- 42
if x == y:
print("values are equal")
else if x > y:
print("x greater than y")
else:
print("x must be less than y")
Answer
x must be less than y
What would be the answer if we instead set x
and y
to:
x <- 75
y <- 9
if x == y:
print("values are equal")
else if x > y:
print("x greater than y")
else:
print("x must be less than y")
Answer
x greater than y
6.5 Caveats
We’re going to cover some more formal processes and syntax. While this won’t impact working with pseudocode, it is important to know when working with the computer.
6.5.1 Order of operations in conditionals
Order of operations is critical for conditionals. The computer will go through each condition in order, so if an early condition is found as true
, the statement will conclude there and not check the other conditions.
if (cheddar == cheese) OR (brie == cheese) OR (broccoli == cheese):
print("This is cheesy")
In this case, because cheddar == cheese
is true
, the computer doesn’t bother checking the other two statements.
6.5.2 Clarity and Order of Operations in math statements
Most of us know the standard order of operation in a math problem (PEMDAS), and most computer languages do, too.
3 + 10 * 2
is solved as 23
(and not 26
)
and so we don’t need parentheses, but it is good practice to use parentheses to make your code more readable and clear.
3 + (10 * 2)
is preferred over 3 + 10 * 2
just as
(cheddar == cheese) OR (brie == cheese) OR (broccoli == cheese)
is easier to read than
cheddar == cheese OR brie == cheese OR broccoli == cheese
6.5.3 Matching parentheses
For complex nested conditionals, be sure to use parentheses, and be sure parentheses are matched properly.
The code below, without a closing parentheses after “equal”, will continue to expect input.
if (x == y)
print("values are equal"
As far as the programming language is concerned, you haven’t finished this if
statement. So, depending on the language, it might wait to run until you have “completed your thought”, so to speak, and provided the syntax (here the end paren )
) indicating that this statement is complete and the program is ready to run.
Here’s another example of fun with parentheses:
if (x == y)
print("values are equal"))
In this case, there is an extra closing parentheses )
after print("values are equal")
that doesn’t have a matching (
anywhere in the statement. The resulting error would look like:
Error: unexpected ')' in:
"if (x == y) {
print("values are equal"))"
6.6 Language examples: Formatting may vary
Much like with for
loops, programming languages may have specific formatting for conditional statements. This may mean certain brackets must be used, new lines are required between sections, or tab indents are needed.
Python requires indentation for code blocks. Code blocks in different structures must be aligned with the same indentation.
Programming structures, such as if
, else
, elif
, or for
expects :
at the end of each statement with the subsequent code block indented by one
if x == y:
print("values are equal")
elif x > y:
print("x greater than y")
else:
print("x must be less than y")
R makes use of curly brackets {}
to indicate each section of an if else
statement. R does not require indentation for code blocks; however, indentation is used because it’s easier for humans to read!
if (x == y) {
print("values are equal")
} else if (x > y) {
print("x greater than y")
} else {
print("x must be less than y")
}
C/C++ syntax looks a lot like R, but requires semicolons at the end of each line to be executed in a code block and uses cout
rather than print
to specify what should be returned in the console.
if (x == y) {
cout << "values are equal";
} else if (x > y) {
cout << "x greater than y";
} else {
cout << "x must be less than y";
}
PHP is very similar to C/C++ with curly brackets and semicolons, but uses echo
rather than cout
.
if (x == y) {
echo "values are equal";
} elseif (x > y) {
echo "x greater than y";
} else {
echo "x must be less than y";
}
Here’s a new language: Bash. This language is often used from the command line to perform operations on files. With Bash, you need to be careful of spaces around your operators and parentheses. (cheatsheets https://ss64.com/bash/if.html https://devhints.io/bash#conditionals)
This Bash script example compares numbers
if (( $x == $y )) ; then
echo "values are equal"
elif (( $x > $y )) ; then
echo "x greater than y"
else
echo "x must be less than y"
fi
This Bash script example compares text
if [[ "$x" == "$y" ]] ; then
echo "the text in x is the same as y"
else
echo "the text in x is not the same as y"
fi