In this tutorial, we will review conditionals and loops in MicroPython, as control structures that allow us to make decisions and repeat actions.
Both conditionals and loops are the main tools for controlling the flow of execution, and constitute the majority of the logic that we will put in our program.
In MicroPython, if
, else
, for
, and while
basically function identically to their equivalents in Python (and, by the way, are quite similar to the rest of the languages).
However, since they are one of the most important parts of your program, let’s briefly review them.
If you want to learn more, check out,
Conditionals
The conditional structures if
and else
allow us to execute a block of code only if a specific condition is met.
In MicroPython, conditionals are implemented using the keywords if
, elif
(optional), and else
.
Basic Syntax of if
The basic structure of an if
conditional is as follows:
if condition:
# Block of code to execute if the condition is true
- Condition: This is a boolean expression that evaluates to
True
orFalse
. - Block of code: This is the set of instructions that are executed if the condition is true.
For example,
temperature = 25
if temperature > 30:
print("It's hot")
In this example, the message “It’s hot” will only be printed if the temperature is greater than 30.
Using else
The keyword else
is used to execute a block of code when the if
condition is not met.
if condition:
# Block of code if the condition is true
else:
# Block of code if the condition is false
Let’s see it with an example,
temperature = 25
if temperature > 30:
print("It's hot")
else:
print("The temperature is pleasant")
In this case, if the temperature is not greater than 30, “The temperature is pleasant” will be printed.
Using elif
The keyword elif
(short for “else if”) is used to evaluate multiple conditions in sequence.
if condition1:
# Block of code if condition1 is true
elif condition2:
# Block of code if condition2 is true
else:
# Block of code if no condition is true
Let’s also see it with a simple example,
temperature = 25
if temperature > 30:
print("It's hot")
elif temperature > 20:
print("The temperature is pleasant")
else:
print("It's cold")
Here,
- The program evaluates multiple conditions
- Executes the block of code corresponding to the first condition that is true.
Loops
The for
and while
loops allow us to repeat a piece of code multiple times. In MicroPython, the most common loops are for
and while
.
for
Loop
The for
loop is used to iterate over a sequence of elements, such as a list or a range of numbers.
for variable in sequence:
# Block of code to execute in each iteration
- Variable: This is a variable that takes the value of each element in the sequence in each iteration.
- Sequence: This is a collection of elements over which to iterate.
Let’s see with an example,
for i in range(5):
print("Iteration:", i)
The for
loop iterates over the numbers from 0 to 4, and in each iteration, the variable i
takes the corresponding value.
This means that this code will print:
Iteration: 0
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
while
Loop
The while
loop is used to repeat a block of code while a condition is true.
while condition:
# Block of code to execute while the condition is true
- Condition: This is a boolean expression that is evaluated before each iteration.
counter = 0
while counter < 5:
print("Counter:", counter)
counter += 1
This code will print:
Counter: 0
Counter: 1
Counter: 2
Counter: 3
Counter: 4
The while
loop runs as long as the value of counter
is less than 5. In each iteration, the counter is incremented by 1.
Loop Control: break
and continue
Sometimes, it is necessary to control the flow of a loop. For this, MicroPython provides the keywords break
and continue
.
- break: Terminates the loop immediately.
- continue: Skips to the next iteration of the loop.
for i in range(10):
if i == 5:
break
print("Iteration:", i)
This code will print:
Iteration: 0
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
The loop stops when i
is equal to 5.
Example with continue
for i in range(5):
if i == 2:
continue
print("Iteration:", i)
This code will print:
Iteration: 0
Iteration: 1
Iteration: 3
Iteration: 4
The loop skips the iteration when i
is equal to 2.
Practical Examples
Controlling an LED with if and while
Suppose we have an LED connected to a GPIO pin of our board. We can use a while
loop to turn the LED on and off at a time interval.
from machine import Pin
import time
led = Pin(2, Pin.OUT) # Set pin 2 as output
while True:
led.value(1) # Turn on the LED
time.sleep(1) # Wait 1 second
led.value(0) # Turn off the LED
time.sleep(1) # Wait 1 second
This code creates an infinite loop that turns the LED on and off every second.
Reading a button with if
If we have a button connected to a GPIO pin, we can use an if
conditional to detect when it has been pressed.
from machine import Pin
button = Pin(4, Pin.IN, Pin.PULL_UP) # Set pin 4 as input with pull-up resistor
while True:
if button.value() == 0: # If the button is pressed
print("Button pressed")
This code detects when the button is pressed (value 0) and displays a message in the console.
Using for to control multiple LEDs
If we have several LEDs connected to different GPIO pins, we can use a for
loop to control them sequentially.
from machine import Pin
import time
leds = [Pin(2, Pin.OUT), Pin(3, Pin.OUT), Pin(4, Pin.OUT)] # List of LED pins
for led in leds:
led.value(1) # Turn on the LED
time.sleep(1) # Wait 1 second
led.value(0) # Turn off the LED
This code turns each LED on and off in sequence, with a 1-second interval between each one.