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
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
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
elseifstatement must come after an
ifstatement (or another
- We can have as many
elseifstatements in a single control structure as we would like!
- Only the first
elseifconditional statement whose boolean expression evaluates to
trueis executed. All other
elsestatements that follow are skipped.
In this program, we are going to print out a different sentence based on what the user’s
score is. Using an
else control structure, we will make four possible outputs.
scoreis equal to
"Winner winner chicken dinner"
scoreis greater than
"Close but not close enough"
scoreis greater than or equal to
"Were you even playing?"
Play with the value of score to see when each print statement is executed.
Why does only one