Imagine we are in the kitchen making a delicious sandwich, but when we check the fridge, we notice that we don’t have ham. We don’t just throw out the sandwich because we don’t have ham. We first will check if we have another option. Luckily we had turkey and can continue to make a sandwich.
When creating a control structure, we often need more than just two options and our basic if
/else
statements are not enough. What we need is an option to check another boolean expression if the first one evaluates to false
. This is done with an elseif
statement.
peopleInRoom = 10 chairsInRoom = 5 if peopleInRoom == 0 then print("No one showed up!") elseif peopleInRoom <= chairsInRoom then print("We have enough chairs") else print("We don't have enough chairs") end
As you can see, the elseif
statement is made of a few parts similar to the if
statement. There are a couple differences from an if
statement and an elseif
statement:
- An
elseif
statement must come after anif
statement (or anotherelseif
). - We can have as many
elseif
statements in a single control structure as we would like! - Only the first
if
orelseif
conditional statement whose boolean expression evaluates totrue
is executed. All otherelseif
orelse
statements that follow are skipped.
Instructions
In this program, we are going to print out a different sentence based on what the user’s score
is. Using an if
/elseif
/elseif
/else
control structure, we will make four possible outputs.
if
:score
is equal to100
then print"Winner winner chicken dinner"
elseif
:score
is greater than80
then print"Close but not close enough"
elseif
:score
is greater than or equal to60
then print"Try again"
else
: print"Were you even playing?"
Play with the value of score to see when each print statement is executed.
Why does only one print
statement show up?