SunFounder ESP32 Starter Kit
The continue Statement
With the continue statement we can stop the current iteration of the loop, and continue with the next:
numbers = [1, 2, 3, 4]
for val in numbers:
if val == 3:
continue
print(val)
>>> %Run -c $EDITOR_CONTENT
1
2
4
The range() function
We can use the range() function to generate a sequence of numbers. range(6) will produce numbers between 0 and 5
(6 numbers).
We can also define start, stop and step size as range(start, stop, step_size). If not provided, step_size defaults to 1.
In a sense of range, the object is “lazy” because when we create the object, it does not generate every number it
“contains”. However, this is not an iterator because it supports in, len and __getitem__ operations.
This function will not store all values in memory; it will be inefficient. So it will remember the start, stop, step size and
generate the next number during the journey.
To force this function to output all items, we can use the function list().
print(range(6))
print(list(range(6)))
print(list(range(2, 6)))
print(list(range(2, 10, 2)))
>>> %Run -c $EDITOR_CONTENT
range(0, 6)
[0, 1, 2, 3, 4, 5]
[2, 3, 4, 5]
[2, 4, 6, 8]
We can use range() in a for loop to iterate over a sequence of numbers. It can be combined with the len() function to
use the index to traverse the sequence.
fruits = ['pear', 'apple', 'grape']
for i in range(len(fruits)):
print("I like", fruits[i])
3.6. 1.6 (Optional) MicroPython Basic Syntax 291