Count and Repeat

Many robotic tasks involve repeating an action over and over again.  Next, we’ll look at two options for repeating code: the for loop and while loop.  The for loop is commonly used for repeating a block of code a certain number of times.  The while loop is used to keep repeating a block of code as long as a condition is true.
 

A for Loop is for Counting

A for loop is typically used to make the statements in a code block repeat a certain number of times.  For example, your cyber:bot may use five different values to make a sensor detect distance, so it needs to repeat a certain code block five times.  For this task, we use a for loop.  Here is an example that uses a for loop to count from 1 to 10 and display the values.

Example script: count_to_ten

  • Enter, name, save, and flash the script count_to_ten to your micro:bit.
#count_to_ten

from microbit import *

for counter in range(1,11):
    display.scroll(counter)

display.scroll("All Done!")

 

How the For Loop Works

The figure below shows the for loop from the last example script count_to_ten.  It labels the elements needed to control how the for loop counts.

Variable: You must have a variable that the code will change while it is executing the for loop. You do not need to declare the variable before this. It is best to name the variable after its purpose. In this example, the variable was a counter, thus it is named counter. It is very common to use the word index or the letter i as the variable in for loops.

The range function: The range(start, stop, step) function is often used with for loops. The start argument sets the initial value of the previously declared variable. The stop argument sets the value the for loop will stop at. Note that the for loop will only execute while the variable is strictly less than the stop value. Thus the stop value is exclusive. The step argument determines how much to increment the variable by for each iteration.

The start and step parameters are optional. If the start argument is not specified, it is set to 0. If the step argument is not specified (like in the example) then it is set to 1.

The first time though the loop, the value of counter is set to 1. So, display.scroll(counter)displays the value 1.  The next time through the loop, Python increments the value counter by 1.  After the display is finished scrolling, the for statement checks to make sure the condition counter < 11 is still true.   Since counter now stores 2, it is true since 2 is less than 11, so it allows the code block to repeat again.  This keeps repeating, but when counter gets to 11, it does not execute the code block because it’s not true according to the counter < 11 condition.

Want to condense your code a little? You can use what is referred to as a list comprehension to put your for loop on one single line. You will learn more about lists in a future chapter.

from microbit import *

[display.scroll(counter) for counter in range(1,11)]

 

Try this: Adjust Initialization and the Range Function

As mentioned earlier, the range(start, stop, step) function defaults to incrementing the variable by 1 each time through the for loop.  You can adjust the step argument so that the for loop is incremented by 2, 5, 1000, -1 or any other integer. Do note that if your step is a negative value, you will need the start value to be larger than the stop value.

  • Rename and save your script as count_higher_in_steps.
  • Replace the for statement in the script with this:
for counter in range(5000, 15000, 1000):
  • Flash the modified script to the micro:bit  and watch the output on the display.

 

A Loop that Repeats while a Condition is True

In later chapters, you’ll use a while loop to keep repeating things while a sensor returns a certain value.  Let’s try counting to ten with a while loop:

  • Enter, name, save, and flash count_to_ten_again to your micro:bit.
# count_to_ten_again

from microbit import *

counter = 0

while counter < 10:
    counter = counter + 1
    display.scroll(counter)

 

Assignment Operators

While loops often make use of certain assignment operators. Such operators take the value on the right-hand side, perform an operation, and assign the result to the value on the left-hand side. Every time you declare a variable, the equal sign (=) is functioning as an assignment operator.  But there are more, less-familiar assignment operators.

For example, the operator (+=) adds the value on the right-hand side of it to the variable on the left-hand side of it. Other similar assignment operators are (-=) for subtraction, (*=) for multiplication, (/=) for division, and (%=) for modulus.

Want to condense your code a little? You can use the assignment operator (+=) to increase the value of counter inside without having to type counter  twice.

while counter < 10:
    counter += 1 
    display.scroll(counter)

 

Using the True Constant

We could also make the loop repeat forever by using the word True instead of the condition counter < 10. Make sure that True starts with a capital T!

while True:
    counter += 1
    display.scroll(counter)

So why does this work?  A while loop keeps repeating as long as the condition that follows the word while is true.  The word True is actually a pre-defined constant, so while True is always true, and will keep the while loop looping.  Notice that the word True is capitalized. Can you guess what while False would do?

 

Your Turn

Try these different while loops in the script count_to_ten_again. What happens?

  • Try while True
  • Try while False
  • Try while 1
  • Try  while 0.

(Spoiler alert: Python treats 1 as True and 0 as False.)