Last lesson we learned about
if else statements and how to get the computer to execute an
else statement when the condition within our
if statement is not met. In this lesson, we will be going over how to create an
else if statement that is linked to the
if else statement we learned the lesson prior.
if else, and
else if statements can be a little confusing in the beginning, but once you see it in use and work through it a couple of times, you will easily be able to understand when and how to use them.
The purpose of having an
else if statement is to add another condition, if the prior conditional statement or statements are false.To demonstrate how the
else if statement works, let’s look at the example shown below.
else statement in the program should look familiar from the previous lessons. However, the 2nd statement that begins with the
else if, you have not seen yet. Luckily, the
else if statement is identical to the if statement, except we just have to add an
else before the
if. You can use an unlimited amount of
else if statements for any condition you want to specify.
It should be noted that every
else if statement must be preceded by a normal
if statement (or another
else if statement if you are using multiple
else if statements..)
In the example, we can see that our first conditional statement returns a true/false value based on whether or not our favorite number is 1. Next, we also added the
else if statement for when our favorite number is 2. However, if our favorite number is any number other than 1 or 2, our
else statement will execute telling us that: Your favorite number isn’t 1 or 2.
If you don’t fully understand the code above, play with it and see how changing the favorite number variable gives you different outputs. If you are unsure about any of the topics we went over this chapter, go back and review them. If statements are the backbone of many programs and an important tool to add to your programmer’s toolbox.