Here is the cleaned Markdown version without emojis, ready for classroom use:
6. Loops with Conditions (micro:bit)
Previously, we used loops like while True: that run forever.
However, we can add a condition to a loop so it stops when the condition is no longer true. This makes it similar to an if statement, but it repeats.
6.1 Example: Counter with a While Loop
1 2 3 4 5 6 7 8 9 10 11 | |
What is happening?
countstarts at 0- The loop runs while
countis less than 10 - Each loop:
- Displays the number
- Waits 500ms
- Increases
countby 1 - Stops when
countreaches 10
Think About It
- How many times does this loop run?
- What changes if we use:
1 | |
6.2 Key Parts of a While Loop
To make a loop work correctly:
-
Tracking variable
1count = 0 -
Condition
1while count < MAX_COUNT: -
Update the variable
1count = count + 1
Common Mistakes
- If the variable never changes, the loop becomes infinite
- If the condition never becomes false, the loop never stops
- Incorrect update such as:
1 | |
6.3 Practice: How Many Times?
How many times will each loop run?
1
1 2 3 4 5 6 | |
2
1 2 3 4 5 6 | |
3
1 2 3 4 5 6 | |
4
1 2 3 4 5 6 | |
5
1 2 3 4 5 6 | |
7. For Loops (Better for Counters)
A for loop is often cleaner when you know how many times to repeat something.
7.1 Example: Using a For Loop
1 2 3 4 5 6 7 8 9 | |
7.2 Why For Loops are Easier
- No need to create
count = 0 - No need to manually increase it
- Automatically runs the correct number of times
7.3 Understanding This Line
1 | |
forstarts the loopcountis the loop variableinis a required keywordrange(MAX_COUNT)generates numbers from 0 toMAX_COUNT - 1
7.4 Key Idea
While loops are best when you do not know how long the loop will run.
For loops are best when you know the number of repetitions.