In MicroPython, for loops are an essential control flow structure used to iterate over sequences such as lists, tuples, dictionaries, ranges, or even strings. They are used when you need to perform repetitive tasks based on each element in a collection or range.
This tutorial will guide you through the basics of using for loops in MicroPython, with plenty of examples to help you understand how to leverage them effectively.
1. Basic Structure of a for Loop
A for loop allows you to iterate over a sequence (like a list or a range). The basic syntax is as follows:
Syntax:
for variable in sequence:
# Code block to execute on each iteration
The variable represents the current element in the sequence during each iteration, and sequence is the collection you’re iterating over.
2. Iterating Over Lists
Lists are one of the most common data types used with for loops. You can iterate over each element in a list.
Example:
# List of fruits fruits = ['apple', 'banana', 'cherry'] # Looping through each element in the list for fruit in fruits: print(fruit)
Output:
apple
banana
cherry
In this example, the loop goes through each item in the fruits list and prints it.
3. Iterating Over Ranges
You can use the range() function to iterate over a sequence of numbers. This is useful when you want to run a loop a specific number of times.
Example 1: Iterating through a Range of Numbers
# Looping from 0 to 4 (range is exclusive of the stop value) for i in range(5): print(i)
Output:
0
1
2
3
4
Example 2: Specifying Start, Stop, and Step in a Range
# Looping with a start, stop, and step for i in range(2, 10, 2): # Start from 2, go up to (but not including) 10, increment by 2 print(i)
Output:
2
4
6
8
4. Iterating Over Strings
A string in MicroPython is a sequence of characters, so you can loop through each character in a string.
Example:
# Looping through each character in a string word = "MicroPython" for char in word: print(char)
Output:
M
i
c
r
o
P
y
t
h
o
n
5. Iterating Over Dictionaries
When iterating over dictionaries, you can loop through the keys, values, or both key-value pairs.
Example 1: Iterating Through Keys
# A simple dictionary person = {'name': 'Alice', 'age': 25, 'city': 'New York'} for key in person: print(key)
Output:
name
age
city
Example 2: Iterating Through Values
# Looping through values for value in person.values(): print(value)
Output:
Alice
25
New York
Example 3: Iterating Through Key-Value Pairs
# Looping through key-value pairs for key, value in person.items(): print(f"{key}: {value}")
Output:
name: Alice
age: 25
city: New York
6. Nested for Loops
You can use a for loop inside another for loop. This is known as a nested loop. This is useful when working with multi-dimensional data, such as lists of lists.
Example:
# A list of lists (2D array) matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] # Nested loop to iterate over rows and columns for row in matrix: for element in row: print(element, end=" ") # Print elements in a single line print() # Newline after each row Output: Copy code 1 2 3 4 5 6 7 8 9
In this example, the outer loop iterates over the rows, and the inner loop iterates over each element in a row.
7. Using break and continue Statements
The break and continue statements allow you to control the flow of the loop.
break terminates the loop entirely.
continue skips the current iteration and proceeds to the next one.
Example 1: Using break
# Loop with break for i in range(10): if i == 5: break # Exit the loop when i is 5 print(i)
Output:
0
1
2
3
4
Example 2: Using continue
# Loop with continue for i in range(5): if i == 2: continue # Skip when i is 2 print(i)
Output:
0
1
3
4
8. else with for Loops
In MicroPython, just like in Python, for loops can have an else clause. The else block is executed after the loop finishes, unless the loop is terminated by a break.
Example:
# Loop with else for i in range(3): print(i) else: print("Loop completed successfully")
Output:
0
1
2
Loop completed successfully
If the loop is interrupted by a break, the else block will not be executed.
Example with break:
# Loop with break and else for i in range(3): if i == 1: break print(i) else: print("Loop completed successfully")
Output:
0
Complete Example: Practical Usage of for Loops
# Loop through a list of numbers and categorize them as odd or even numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9] for number in numbers: if number % 2 == 0: print(f"{number} is even") else: print(f"{number} is odd")
Output:
1 is odd
2 is even
3 is odd
4 is even
5 is odd
6 is even
7 is odd
8 is even
9 is odd
Conclusion
for loops in MicroPython offer a powerful way to iterate through different data structures. You can easily loop through lists, ranges, strings, and dictionaries, as well as perform nested loops. Controlling the flow with break and continue, and using an else statement in combination with a loop, provides further control over how your program executes.