Sometimes we can have more than two possible scenarios which need a different code to be ran. We can add else if statements to allow for as many outcomes as we want:
var language = "Python"
if(language == "Scala") {
println("It's super popular!")
}
else if(language == "Python") {
println("It's so simple!")
}
else if (language == "Java") {
println("It's pretty hardcore!")
}
else {
println("It's exotic!")
}
In the example above, language == "Scala" evaluates to false, so we move on and enter the following else if.
There, language == "Python" evaluates to true, so we execute what's inside that block and print "It's so simple!".
The rest of the conditions are not evaluated.
In case none of the conditions evaluates to true, then the code in the final else statement would execute. For example, if language was "Go", the program would have printed "It's exotic!"
Assignment
Follow the Coding Tutorial and let's write some chained conditionals.
Hint
Look at the examples above if you get stuck.
Free plan: 30 tutor messages. Premium is unlimited.