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.
The script 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 statement.
If the condition (a > b) is True, it executes the if statement’s code block: display.scroll("a is greater than b"). If it so happens a is actually not greater than b, it executes the else code block instead: display.scroll("a is not greater than b").
#simple_decision from microbit import * a = 89 b = 42 if a > b: display.scroll("a is greater than b") else: display.scroll("a is not greater than b")
Notice again that the line beneath if a > b: is indented. Also, the line beneath else: is indented. Python needs these lines to be indented to determine which line to execute when the condition is true, and which line to execute when the condition is false. It is good practice to indent 4 spaces. Many Python IDEs (integrated development environments, such as Mu) place 4 spaces in your code when you press the tab key.
Maybe you only need a message when a is greater than b. If that’s the case, you could cut out the else statement and its code block. So, all your code would need is the one if statement, like this:
a = 89 b = 42 if a > b: display.scroll("a is greater than b")
Maybe your program needs to monitor for three conditions: greater than, less than, or equal. For this, you could use an if…elif…else statement. Note that elif is short for "else if."
#more_decisions from microbit import * a = 89 b = 42 if a > b: display.scroll("a is greater than b") elif a < b: display.scroll("b is greater than a") else: display.scroll("a is equal to b")
You can chain more elif statements after if. The example above only uses one elif 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 statment gets left behind.
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 statement’s block will execute only if a is greater than 50 AND b is less than 50:
if a > 50 and b < 50: display.scroll("Values in normal range")
Another example: this one prints the warning message if a is greater than 100 OR b is less than zero.
if a > 100 or b < 0: display.scroll("Danger Will Robinson!")