Skip to content

Commit 8786618

Browse files
committed
loops pt2
1 parent fe46696 commit 8786618

File tree

1 file changed

+45
-50
lines changed
  • content/micropython/03.micropython/01.basics/02. loops

1 file changed

+45
-50
lines changed

content/micropython/03.micropython/01.basics/02. loops/loops.md

+45-50
Original file line numberDiff line numberDiff line change
@@ -55,26 +55,24 @@ MicroPython is officially supported on several Arduino boards. Here’s a list o
5555

5656
MicroPython supports two primary loop structures, each with a specific purpose:
5757

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.
5959

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.
6161

6262
To better understand these loops, let’s imagine them as tasks at the supermarket:
6363

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.
6565

6666
![How for loops work.]()
6767

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.
6969

7070
![How while loops work.]()
7171

7272
## For Loops
7373

7474
The `for` loop is used for iterating over a sequence. It automatically retrieves each item in the sequence one after another.
7575

76-
### Syntax
77-
7876
```python
7977
for variable in sequence:
8078
# Code block to execute
@@ -86,35 +84,31 @@ for variable in sequence:
8684
- **`sequence`**: The collection (like a list, tuple, or string) over which the loop iterates.
8785
- **Code block**: The indented block of code that runs on each iteration.
8886

89-
### Example: Iterating Over "Arduino" with a `for` Loop
87+
### Example Code
9088

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.
9390

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 in range(5):
93+
print(i)
9994
```
10095

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:
10997

98+
```
99+
0
100+
1
101+
2
102+
3
103+
4
104+
```
110105

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.
111107

112-
## Using a `while` Loop
108+
## While Loops
113109

114110
A `while` loop continues to execute as long as a specified condition is true.
115111

116-
### Syntax of a `while` Loop
117-
118112
```python
119113
while condition:
120114
# Code block to execute
@@ -124,34 +118,35 @@ while condition:
124118
- **`condition`**: A boolean expression evaluated before each iteration; if `True`, the loop continues.
125119
- **Code block**: The indented block of code that runs on each iteration.
126120

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.
128124

129125
```python
130126
import time
127+
counter = 0
131128

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+
while True:
130+
counter += 1
131+
print('Number of iterations: ' + str(counter))
132+
time.sleep(1)
142133
```
143134

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:
145142

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+
```
155150

156151
## Control Statements
157152

@@ -206,9 +201,9 @@ Running this script will result in:
206201

207202
## Conclusion
208203

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.
210205

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)
212209

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

Comments
 (0)