15. EXT: nested for-loops using the range function

15.1. Set pixels

Read the above examples before reading further to see how they illustrate nested loops.

15.2. Using pixels in nested for-loops

In the code below, the outer loop iterates over x values from 0 to 4.
For each x value, the inner loop iterates over y values from 0 to 4.
So when x is 0, y goes from 0 to 4, turning on each pixel in the first column.
This repeats for the other columns.
from microbit import *

for x in range(5):
    for y in range(5):
        display.set_pixel(x, y, 9)
        sleep(100)

Tasks

  1. Write code that turns on the pixels one row at a time from the top.

  2. Write code that turns on the pixels one row at a time from the bottom.

Write code that turns on the pixels one row at a time from the top.

from microbit import *

for y in range(5):
    for x in range(5):
        display.set_pixel(x, y, 9)
        sleep(100)

Write code that turns on the pixels one row at a time from the bottom.

from microbit import *

for y in range(4,-1,-1):
    for x in range(5):
        display.set_pixel(x, y, 9)
        sleep(100)

15.3. Advanced: nested for-loops with range function

What does this code do?
What are the values of start_num in the nested loop?
from microbit import *

while True:
    for start_num in range(4):
        for n in range(start_num, start_num + 5, 2):
            display.scroll(n, delay=40)

Tasks

  1. Write code using nested range functions to scroll 0, 3, 6, 9, 1, 4, 7, 10.

  2. Write code using nested range functions to scroll 0, 5, 1, 6, 2, 7, 3, 8.

Write code using nested range functions to scroll 0, 3, 6, 9, 1, 4, 7, 10.

from microbit import *

while True:
    for start_num in range(2):
        for n in range(start_num, start_num + 10, 3):
            display.scroll(n, delay=40)

Write code using nested range functions to scroll 0, 5, 1, 6, 2, 7, 3, 8.

from microbit import *

while True:
    for start_num in range(5):
        for n in range(start_num, start_num + 6, 5):
            display.scroll(n, delay=40)