For Loops in MicroPython on Raspberry Pi Pico

Posted

in

by

For loops are one of the most commonly used loops in programming, including MicroPython on Raspberry Pi Pico. They allow you to repeat a set of instructions a specific number of times, making your code more efficient and concise.

In MicroPython, a for loop is used to iterate over a sequence of values, such as a list, tuple, or string. The general syntax for a for loop in MicroPython is as follows:

for variable in sequence:
    # Code to execute for each item in the sequence

Here, variable is a temporary variable that takes on the value of each item in the sequence. The code block under the for statement is executed for each item in the sequence, with variable taking on the value of each item in turn.

For example, let’s say we have a list of numbers and we want to print each number in the list:

numbers = [1, 2, 3, 4, 5]

for num in numbers:
    print(num)

In this code, num takes on the value of each item in the numbers list, and the print statement outputs each number in turn.

In addition to lists, for loops can also be used with other sequences such as tuples and strings. For example:

name = "John"

for char in name:
    print(char)

This code outputs each character in the string name, one character per line.

You can also use the built-in range() function with for loops in MicroPython. The range() function returns a sequence of numbers starting from 0 (by default) and incrementing by 1, up to a specified number. For example:

for i in range(5):
    print(i)

This code outputs the numbers 0 through 4, one number per line.

You can also specify a starting value and a step size for the range() function. For example:

for i in range(1, 10, 2):
    print(i)

This code outputs the odd numbers from 1 to 9, one number per line.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *