Make Decisions
Your cyber:bot will need to make a lot of navigation decisions based on sensor inputs. Computer programs tend to make decisions by testing whether or not a condition is true, and if it is true do one thing, else, do another.
For making these kinds of decisions, comparison operators come in handy.
- compare-equals (==)
- greater than (>)
- less than (<)
- greater than or equal to (>=)
- less than or equal to (<=)
Simple Decisions
The project simple_decision demonstrates single-operation decision-making. It compares the value of a to b, and sends a message to tell you whether or not a is greater than b, with an if…else block.
If the condition (a > b) is True, it executes the if block’s code block: show string (“a is greater than b”). If it so happens that a is not greater than b, it executes the else code block instead: show string (“a is not greater than b”).
Example project: simple_decision
- Enter and name the project simple_decision into the code editor exactly as shown.
- Flash the project to the micro:bit.
- Look at the display to make sure you got the right message.
- Try swapping the assigned values for a and b.
- Re-flash the program and verify that it is displaying the other message.
Make sure you have the proper messages within the proper if…else container as shown above.
Try This – Only if
Maybe you only need a message when a is greater than b. If that’s the case, you could cut out the else block and its code. So, all your code would need is the one if block, like this:
- Modify and re-flash your code as shown above.
Your Turn
- Make a project using the compare-equals operator (=) that displays a message only when a is equal to b.
More Decisions
Maybe your program needs to monitor for three conditions: greater than, less than, or equal. For this, you could use an if…else if…else block.
Example project: more_decisions
- Enter, name, and flash the project more_decisions to your micro:bit.
You can chain more else if blocks after if. The example above only uses one else if but you could use more. Each condition is tested in order, and after the first true condition is found, its code block is executed and the rest of the block gets left behind.
Your Turn
- Make a project that uses two or more else if blocks that are true, with code blocks that display messages.
- Flash the project to prove that only the first true else if condition’s message gets displayed.
Boolean Operators
Sometimes, you need to test whether two or more conditions are true at the same time. A program can handle multiple conditions with the boolean operators, such as and and or. For example, this block’s code will execute only if a is greater than 50 AND b is less than 50:
Another example: this one prints the warning message if a is greater than 100 OR b is less than zero.
Your Turn
- Try the above blocks in a project.