What are conditional statements?
Conditions or conditional statements allow our program to check if there are certain situations present. If they are, then we have instructions for the computer to run. Generally, people call conditions "if, then, else" statements as they involve us using those terms. For example, let's say the situation our program is monitoring is the temperature in our house. We might write our conditions like this:
IF the temperature in our house is greater than 20 degrees Celsius,
THEN turn the heating off.
ELSE, turn the heating on.
When you think about it, we use conditions all of the time in our everyday lives. Try out the unplugged activity below that helps us understand the use of 'if’, ‘then’ and ‘else’ to run certain commands.
Try this out at home: You can call this out with family members in your home or you can play along yourself as you read each line.
1) Read out the following sentences. You should respond based on how the statement applies to you.
For example, with the sentence "If you love to code, then put your right hand in the air, else leave your hand down", I would put my right hand in the air!
- If your name begins with the letter 'C', then clap once, else clap twice.
- If your hair is brown, then point to your head, else put your finger on your chin.
- If the month of your birthday is January, February or March, then whistle, else click your fingers.
- If you have a pet at home, then do three frog leaps, else do three jumping jacks.
- If you have blue eyes, then shout ‘blue’, else if you have brown eyes, then shout ‘brown’, else shout ‘neither’.
- If you had toast with your breakfast, then stick out your tongue, else if you had cereal, then hold your right ear, else hold your left ear.
- If your name begins with a letter from ‘A’ to ‘H’, then raise your right hand, else if your name begins with a letter from ‘I’ to ‘Q’, then raise your left hand, else leave your hands on your lap.
- If your favourite hobby is to play sport, then jump in the air twice, else if your favourite hobby is playing a musical instrument, then pretend to play the guitar, else if your favourite hobby is reading, then hold your two hands out on front of you with your palms facing up, else put your two hands on your hips.
2) Now, can you create your own 'if, then, else' statements to test out on someone in your house? The above list might help you come up with some other conditions of your own.
As we build levels into our game, conditional statements are going to be really useful. So let's begin to level up with our second game of the series.
Once again, we have added lots of code and an entire new level to our game. In the next lesson, we will be adding level three. Similarly to last week, it is best that you have thought about how you want your level three to look and work. So, download the PDF file to help guide you with your plans for the next level!