Checking Multiple Conditions with If-Else-If

Name Code (Block) Code (Text)
Checking Multiple Conditions with If-Else-If

How does it work?

The if-else-if command lets you check multiple boolean conditions. The computer will check conditions in the order they are written until one of the boolean expressions evaluates to true. The code associated with that boolean expression will be run, but all others will be skipped. If none of the expressions evaluates to true then the code inside the else command will be run.

Most Specific Cases First

When writing an if-else-if statement you want to put the most specific cases first. In the temperature example above you want to check for temperatures over 100 degrees first. Afterwards the code checks for temperatures above 90 degrees, but because of the order the code is written you know that none of temperatures you'll find there are above 100 degrees. After all you would have caught them in the previous if-statement. This means you can be confident any temperatures you catch there will be between 90 and 100 degrees. As you continue through the if-else-if statement you use the same logic to check for different ranges of temperature.

A Broken Example: Most Specific Cases Last

This is a broken example that shows what happens if you start checking for temperatures in reverse order, most specific cases last.

Think through what would happen when this code runs for the temperature 82 degrees. You would want the output to say "It's hot". If you look at the first boolean expression, however, you'll notice that 82 is higher than 60 degrees, making that boolean expression evaluate to true. As a result the code will output "It's cool". This is because the first expression is not actually the most specific.

Found a bug in the documentation? Let us know at documentation@code.org