Hello everyone! In this activity, we’ll learn about conditional statements. Afterwards, you’ll know what conditional statements are, and how to create them in Blockly!
Before we begin:
- Make sure that you have your KINI robot, and that it is connected to the internet.
- Open the app, and go to the Blockly tab by clicking the Blockly button in the bottom right corner. We will be using the two Repeat blocks to create our code.
- Understand the basics of Blockly - if you don’t, go to the “Introduction to Blockly” activity before this one.
What is a conditional statement?
- Conditional statements are a type of coding instruction that depend on if a condition is met
- Conditional statements can be used to control KINI in Blockly
- Depending on if a condition is true or false, KINI will do a certain action
How to use conditional statements in Blockly:
- To find all of the Conditional Statement blocks, go to the light blue Logic tab on the left side of the screen.
- For this example, we will use the “If/Do/Else” block. Click it for it to appear beside the two repeat blocks.
Drag the “If/Do/Else” block and snap it into place in the Repeat Forever block
- Typically, the Repeat Forever block is used for conditional statements, as instead of testing for the condition one time, KINI will always test if the condition is true.
- The condition goes into the "If" part of the block
- To find condition blocks, go to the green Sensors tab. This example uses the distance sensor.
The action that happens if the condition is true (or met) goes into the “Do” part of the block
- To find action blocks, go to the orange KINI tab. This example uses a rotate left block
- The action that happens if the condition is false (or not met) goes into the “Else” part of the block
- To find action blocks, go to the orange KINI tab. This example uses a move forward block
The code in the example tells us that the condition is that KINI is less than 10cm from an object. If that condition is true (or met), KINI will rotate left for one second to avoid the object. If the condition is false (or not met), KINI will move forward. Since the entire conditional statement is in the repeat forever block, this will happen continually, meaning that KINI will move around the room avoiding objects.
Congratulations everyone! You just learnt what a conditional statement is, and how to make your own conditional statements in Blockly. You can try out this same code, and even try adding your own conditions to improve the code.
Now that you’ve learnt about conditional statements each time you code KINI, try to use conditional statements to solve problems. Good luck, and have fun coding!