Buttons and Conditionals
# Buttons and Conditionals from microbit import *
while True: if button_a.is_pressed(): display.show(Image.HAPPY) elif button_b.is_pressed(): display.clear()
Conditional statements are prevalent in every programming language because they have a multitude of uses. the idea behind them is that IF a condition is true, THEN another action or block of code will trigger and execute. In Python, conditional statements take the following format (elif stands for else if):
if something is True: # DO something elif some other thing is True: # DO something else else: # DO the final option
The second tool, loops, goes hand-in-hand witht he computational thinking style that is required for conditional statements. There are two main types of loops: while loops and for loops. For loops execute a specific block of code a specific number of times. While loops, loop a specific block of code WHILE a certain condition remains true. Python uses the format below for while loops.
while something is True: # DO this code
The main loop is an indefinite loop. This can be set up easily with the following line:
This block of code will repeat itself while true is true. This tool can be used any time you want a section of a program to loop or stay activated until a certain event is triggered. In this case, we want a program that responds to the button presses to stay active as long as power is connected to the micro:bit, so we use while True:
The final command required is tied to using the buttons. Each button (button_a and button_b) is its own object and therefore has its own commands programmed to work with it. In this case, the command is button_a.is_pressed(). This command will return a value of "true" if the button is being pressed, which works well with the conditional statements from earlier in the lesson. Once they have this line, you can program a button press to do anything you already know how to do! for example:
If button_a.is_pressed(): display.show(boat) elif button_b.is_pressed(): display.clear()
This code displays the boat image created in a previous activit IF the A button is being pressed, and clears the display IF the B button is being pressed.
The code provided above runs only once upon start up, and this is where the while True: loop comes in to play. For this code to run as long as the micro:bit has power, only one line needs to be added and indents need to be in order.