Learn

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 an if statement (or another elseif).
  • We can have as many elseif statements in a single control structure as we would like!
  • Only the first if or elseif conditional statement whose boolean expression evaluates to true is executed. All other elseif or else statements that follow are skipped.

Instructions

1.

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 to 100 then print "Winner winner chicken dinner"
  • elseif: score is greater than 80 then print "Close but not close enough"
  • elseif: score is greater than or equal to 60 then print "Try again"
  • else: print "Were you even playing?"
2.

Play with the value of score to see when each print statement is executed.

Why does only one print statement show up?

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?