You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: content/micropython/03.micropython/01.basics/02. loops/loops.md
+45-50
Original file line number
Diff line number
Diff line change
@@ -55,26 +55,24 @@ MicroPython is officially supported on several Arduino boards. Here’s a list o
55
55
56
56
MicroPython supports two primary loop structures, each with a specific purpose:
57
57
58
-
-**`for` loops**: These loops iterate over a predefined sequence, such as a list, tuple, or string. The loop automatically retrieves each item in the sequence, one at a time, and performs actions until every item has been handled.
58
+
-**`for` loops**: for loops iterate over a predefined sequence, such as a list, tuple, or string. The loop automatically retrieves each item in the sequence, one at a time, and performs actions until every item has been handled.
59
59
60
-
-**`while` loops**: These loops continue executing as long as a specified condition is true. Unlike `for` loops, which depend on a sequence, `while` loops rely on a conditional expression that determines when the loop should stop.
60
+
-**`while` loops**: while loops continue executing as long as a specified condition is true. Unlike `for` loops, which depend on a sequence, `while` loops rely on a conditional expression that determines when the loop should stop.
61
61
62
62
To better understand these loops, let’s imagine them as tasks at the supermarket:
63
63
64
-
-**`for` loops**: Imagine walking down a supermarket aisle with a shopping list that specifies exactly how many items to pick up, one by one, in order. Once you’ve gathered all the items on your list, your task is complete. This is like a `for` loop iterating over a sequence, handling each specified item one at a time.
64
+
-**for loops** - imagine walking down a supermarket aisle with a shopping list that specifies exactly how many items to pick up, one by one, in order. Once you’ve gathered all the items on your list, your task is complete. This is like a `for` loop iterating over a sequence, handling each specified item one at a time.
65
65
66
66
![How for loops work.]()
67
67
68
-
-**`while` loops**: Imagine going to the supermarket to buy a certain product that’s on sale, as long as it stays in stock. You keep coming back, day after day, until the sale ends or the stock runs out. In a `while` loop, you keep “coming back” as long as a condition (like the sale continuing) remains true.
68
+
-**while loops** - imagine going to the supermarket to buy a certain product that’s on sale, as long as it stays in stock. You keep coming back, day after day, until the sale ends or the stock runs out. In a `while` loop, you keep “coming back” as long as a condition (like the sale continuing) remains true.
69
69
70
70
![How while loops work.]()
71
71
72
72
## For Loops
73
73
74
74
The `for` loop is used for iterating over a sequence. It automatically retrieves each item in the sequence one after another.
75
75
76
-
### Syntax
77
-
78
76
```python
79
77
for variable in sequence:
80
78
# Code block to execute
@@ -86,35 +84,31 @@ for variable in sequence:
86
84
-**`sequence`**: The collection (like a list, tuple, or string) over which the loop iterates.
87
85
-**Code block**: The indented block of code that runs on each iteration.
88
86
89
-
### Example: Iterating Over "Arduino" with a `for` Loop
87
+
### Example Code
90
88
91
-
```python
92
-
import time
89
+
Let's try out making a for loop. In this example, we set `i` which stands for *iteration*, in a range of 5.
93
90
94
-
cycle =1
95
-
for letter in"Arduino":
96
-
print(f"{cycle} - {letter} - printed with for loop")
97
-
cycle +=1
98
-
time.sleep(3)
91
+
```python
92
+
for i inrange(5):
93
+
print(i)
99
94
```
100
95
101
-
Let's take a look at what's included in this code example:
102
-
103
-
-`import time` - we import the `time` module to use the `sleep()` function for delays.
104
-
-**Initialize `cycle` Variable**: We start a `cycle` counter at 1.
105
-
-**`for letter in "Arduino"`**: The loop iterates over each character in the string `"Arduino"`, assigning each character to the variable `letter`.
106
-
-**Print Statement**: Outputs the cycle number, the current letter, and mentions that it's printed with a `for` loop.
107
-
-**Increment `cycle`**: Increases the cycle counter by 1 after each iteration.
108
-
-**`time.sleep(3)`**: Pauses the program for 3 seconds before the next iteration.
96
+
Running this script will result in printing `i` for five times. Each time the loop is run, `i` is increased, so in the REPL, we should see:
109
97
98
+
```
99
+
0
100
+
1
101
+
2
102
+
3
103
+
4
104
+
```
110
105
106
+
This is because we start counting from 0. So the first time the loop runs, we print `0`, the second time it runs `1` and so on.
111
107
112
-
## Using a `while` Loop
108
+
## While Loops
113
109
114
110
A `while` loop continues to execute as long as a specified condition is true.
115
111
116
-
### Syntax of a `while` Loop
117
-
118
112
```python
119
113
while condition:
120
114
# Code block to execute
@@ -124,34 +118,35 @@ while condition:
124
118
-**`condition`**: A boolean expression evaluated before each iteration; if `True`, the loop continues.
125
119
-**Code block**: The indented block of code that runs on each iteration.
126
120
127
-
### Example: Iterating Over "Arduino" with a `while` Loop
121
+
### Example Code
122
+
123
+
Let's try making a while loop! In the example below, we have a counter, which we print to the REPL. This is to track how many times the loop has run. We pause between each print using the `time.sleep(1)` function, so that it is easier to read in the REPL.
128
124
129
125
```python
130
126
import time
127
+
counter =0
131
128
132
-
word ="Arduino"
133
-
index =0
134
-
cycle =1
135
-
136
-
while index <len(word):
137
-
letter = word[index]
138
-
print(f"{cycle} - {letter} - printed with while loop")
139
-
index +=1
140
-
cycle +=1
141
-
time.sleep(3)
129
+
whileTrue:
130
+
counter +=1
131
+
print('Number of iterations: '+str(counter))
132
+
time.sleep(1)
142
133
```
143
134
144
-
**Explanation:**
135
+
In this example, we used:
136
+
137
+
-`while True:` - this keeps a while loop running forever.
138
+
-`print('Number of iterations: ' + str(counter))`, to print out the current iteration.
139
+
- because we cannot mix numeric values with strings when using the `print()` function, we need to use `str(counter)` when printing to the REPL.
140
+
141
+
The result will be an infinite loop, that will print the current iteration:
145
142
146
-
-**Initialize Variables**:
147
-
-`word`: The string we're iterating over.
148
-
-`index`: Starts at 0, used to access each character in `word`.
149
-
-`cycle`: Counts the number of iterations.
150
-
-**`while index < len(word)`**: The loop continues as long as `index` is less than the length of `word`.
151
-
-**Retrieve Letter**: `letter = word[index]` gets the character at the current index.
152
-
-**Print Statement**: Outputs the cycle number, the current letter, and mentions that it's printed with a `while` loop.
153
-
-**Increment Counters**: Increases `index` and `cycle` by 1.
154
-
-**`time.sleep(3)`**: Pauses the program for 3 seconds before the next iteration.
143
+
```python
144
+
Number of iterations: 10
145
+
Number of iterations: 11
146
+
Number of iterations: 12
147
+
.....
148
+
Number of iterations: 99999# this loop has been running for a long time..
149
+
```
155
150
156
151
## Control Statements
157
152
@@ -206,9 +201,9 @@ Running this script will result in:
206
201
207
202
## Conclusion
208
203
209
-
Loops are essential for automating repetitive tasks in MicroPython. Understanding how to use different loop structures allows you to write more efficient and effective code. In these examples, we've demonstrated how to iterate over the string "Arduino" using various loop methods, printing each letter with a delay to observe the output in real time.
204
+
Loops are essential for automating repetitive tasks in MicroPython. Understanding how to use different loop structures allows you to write more efficient and effective code.
210
205
211
-
**Try Modifying the Examples**
206
+
In these examples, we've demonstrated how to create loops that can:
207
+
- Run *for* a specific amount of iterations (for loops)
208
+
- Loops that can run *while* a condition is met (while loops)
212
209
213
-
-**Different Strings**: Replace `"Arduino"` with another word to see how the loops handle different sequences.
214
-
-**Additional Information**: Include more details in the print statement, such as the ASCII value of each letter.
0 commit comments