Chapter 1 – Introduction to Blockly with Zumis
1.6 – Selection Code Structures
So far we’ve learned about conditionals using basic if statements and comparators and how they can be used to create a remote control.
Let’s do a quick review:
What is logic?
In programming, logic refers to the flow of code that is used to execute a program. It can be a combination of various types of conditions that are created to fit a scenario.
Think about a traffic light. If you were to program a traffic light, you would have to write different code for the three different lights, based on what they mean. Can you think of any other examples?
If statements
An if statement is a conditional statement that is written to test a condition in a program, and if the specified condition is met, then only is the code inside the if statement run.
If-else statements
Let’s say that you had multiple conditions, however, you also wanted the program to do something if none of the conditions were met. In such a case, you can use if-else statements.
Recall that “Else” has no condition! This is because “else” is the last option when using if-else statements. When a computer reaches the “else” option after checking all the other conditions, then the else condition is automatically true and will run its statements.
One way to use “else” would be when something needs to happen when a condition is false. When the “if” condition is false and nothing needs to happen, don’t use an “else”.
Here is an example. Let us set X to 36 and Y to 15. Is X > Y? In other words, is 36 > 15? This is true, so move forward at 40 speed. What if this is false? That is why we use else if statement. In the case that the first if statement is false, we can set other statements to check. Now what happens if all if and else if statements return false? Then the else statement will be executed.
Keep in mind that only one of these can be true and will run. If the if statement and else if statement both return true, only the first one (if statement) will run and the other one will be skipped.
Multiple if statements
Inside our code, we can have multiple if statements. Typically, each if statement has its own condition, and so if you are testing for multiple conditions, you can create an if statement for each condition.
Implementing logic using if statements
When implementing logic using if statements, a general rule of thumb is too look for all the conditions in your logic. Ask youself, at which points are you comparing items in your code? Are there any points, where you are checking if a certain variable of value is True or False? All of these logic portions can be written using if statements.
Activity
Change this Blockly code to meet these conditions:
* Celebrate if X is greater than Y
* If X and Y are equal, tell Zumi to stop
* If X is less than Y, tell Zumi to reverse.
Demo
Questions