Loops are an essential part of any programming language, including MicroPython on Raspberry Pi Pico. They allow you to execute a block of code repeatedly, saving you time and effort. In this article, we’ve introduced you to the two types of loops in MicroPython: for loops and while loops.
What are Loops?
A loop is a programming construct that allows you to execute a block of code repeatedly until a specific condition is met. There are two types of loops in MicroPython: for loops and while loops.
For Loops
A for loop is used when you want to execute a block of code a fixed number of times. The syntax of a for loop in MicroPython is as follows:
for variable in sequence:
# Code to execute
The variable is assigned to each element of the sequence in turn, and the code inside the loop is executed. Here’s an example:
for i in range(5):
print(i)
This code will print the numbers from 0 to 4.
While Loops
A while loop is used when you want to execute a block of code repeatedly until a specific condition is met. The syntax of a while loop in MicroPython is as follows:
while condition:
# Code to execute
The code inside the loop will be executed repeatedly until the condition becomes false. Here’s an example:
i = 0
while i < 5:
print(i)
i += 1
The code first initializes the value of i to 0. Then it enters the while loop and checks if the value of i is less than 5. Since i is initially 0, the condition is true and the loop begins.
The loop prints the current value of i using the print() function and then increments the value of i by 1 using the += operator. This process repeats until the value of i is no longer less than 5, at which point the loop ends and the program continues with the rest of the code.
When you run this code in a MicroPython environment such as Thonny IDE, the output will be:
0 1 2 3 4
This is because the loop executes five times, with the value of i being printed on each iteration.
Leave a Reply