Why Should I Learn About Conditionals?
What are Conditionals?
Conditionals are just what the name implies — they are statements that run only when certain conditions are true.
While the most popular conditional statement for new users is probably the if/else block (shown above), there are other formats for these conditionals, as well.
Only one section of an if-statement, if/else-statement, or if/elseif/else-statement runs for any given condition. If the first condition is true, the code in the top runs and everything else is ignored. If the else if is true, that means the first condition was not true, so the else if segment will run and everything else will be ignored.
There can be many else if clauses, and each will be checked in the order that you place them, assuming no conditions above were met.
Finally, if (and only if) none of the above conditions are true, the else condition will kick in and the last segment of code will run.
If you don’t want any code to run when no conditions are true, you can leave off the else clause.
Why should I care?
Conditionals provide your program with the power to make a choice. Without conditionals, computers wouldn’t be able to make decisions based on real-time information.
Want your game to end when lives are gone? Want to call Player 1 the winner when their score is higher than Player 2 at the end of the game? You’ll need conditionals!
Tell me more!
Remember the idea of “sister concepts” that I introduced in the article on loops? Yep, conditionals have a sister concept too…Events!
Conditionals run code if something special is true. Events run code when something special happens. It’s totally possible that a solution might be programmed using either or both of these.
For example, take a look at the two chunks of code below. Both will end the game in the case where the main player (mySprite) runs into the enemy (otherSprite).
The code on the left ends the game if it becomes true that the sprites overlap…and the code on the right runs when the computer recognizes that the two sprites overlap.
The main difference here is that the event persistently listens in the background until that moment when something happens — while the conditional only checks if something is true one time and needs to be put in a loop to continue checking repeatedly.
In Conclusion
Conditionals might take some getting used to, but they are extremely powerful tools when it comes to making exciting and ever-changing programs.