14. For loops using the range function
See: `<https://www.w3schools.com/python/python_for_loops.asp
14.1. Range function starting at 0
- range(stop_value)
Returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends before the
stop_valuenumber.
from microbit import *
while True:
for n in range(3):
display.scroll(n, delay=80)
sleep(500)
Tasks
Using the range function, write a for-loop that displays the numbers from 0 to 3.
Using the range function, write a for-loop that displays the numbers from 0 up to but not including 5.
Using the range function, write a for-loop that displays the numbers from 0 to 3.
from microbit import *
while True:
for n in range(4):
display.scroll(n, delay=80)
sleep(500)
Using the range function, write a for-loop that displays the numbers from 0 up to but not including 5.
from microbit import *
while True:
for n in range(5):
display.scroll(n, delay=80)
sleep(500)
14.2. Adding to the range function variable
from microbit import *
while True:
for n in range(3):
display.scroll(n + 1, delay=80)
sleep(500)
Tasks
Using the range function, write a for-loop that displays the numbers from 1 to 5.
Using the range function, write a for-loop that displays the numbers from 2 to 5.
Using the range function, write a for-loop that displays the numbers from 1 to 5.
from microbit import *
while True:
for n in range(5):
display.scroll(n + 1, delay=80)
sleep(500)
Using the range function, write a for-loop that displays the numbers from 2 to 5.
from microbit import *
while True:
for n in range(4):
display.scroll(n + 2, delay=80)
sleep(500)
14.3. Subtracting from the range function variable
from microbit import *
while True:
for n in range(4):
display.scroll(n - 1, delay=80)
sleep(500)
Tasks
Using the range function, write a for-loop that displays the numbers from -1 to 1.
Using the range function, write a for-loop that displays the numbers from -2 to 2.
Using the range function, write a for-loop that displays the numbers from -1 to 1.
from microbit import *
while True:
for n in range(3):
display.scroll(n - 1, delay=80)
sleep(500)
Using the range function, write a for-loop that displays the numbers from -2 to 2.
from microbit import *
while True:
for n in range(5):
display.scroll(n - 2, delay=80)
sleep(500)
14.4. Multiplying the range function variable
from microbit import *
while True:
for n in range(3):
display.scroll(n * 2, delay=80)
sleep(500)
Tasks
Using the range function, write a for-loop that displays the numbers 0, 3, 6, 9.
Using the range function, write a for-loop that displays the numbers 0, -1, -2, -3.
Using the range function, write a for-loop that displays the numbers 0, 3, 6, 9.
from microbit import *
while True:
for n in range(4):
display.scroll(n * 3, delay=80)
sleep(500)
Using the range function, write a for-loop that displays the numbers 0, -1, -2, -3.
from microbit import *
while True:
for n in range(4):
display.scroll(n * -1, delay=80)
sleep(500)