MicroPython 'while' Loops

Contents


Introduction

MicroPython is a “slim” version of Python specifically designed with a small footprint to efficiently run on memory constrained microcontrollers.

Computer languages provide a variety of statement types. Programmers would expect as a minium to find:

This article explores MicroPython's while looping statement.

Simple Looping with while

In a while loop, a condition is first checked. If it is True, then code in the loop body is executed. This process will repeat until the condition becomes False.

Syntax

while <condition>:
  <loop body>

          
Python while Statement
FIG 1 - Python while Statement
Example 1: while statement:

# Demonstrates looping with 'while'

# The program sums together the numbers
# from 1 to 10,000 and prints the result.

sum = 0
counter = 1

while (counter <= 10000):
    sum += counter
    counter += 1
    
print('Sum of 1..10,000 is', sum)

          
Output:

Sum of 1..10,000 is 50005000

            

Note that the loop statement(s) to be executed if the conditional expression evaluates to True are indented. It is important to remember that this is how a code block is defined in Python. The Python language does not have a block end statement, unlike many other languages.

Control Statements

Loop control statements are used to change execution from its normal sequence. Python has three loop control statements.

Table 1: MicroPython - Loop Control Statements
Control Statement Description
break Used to exit a while loop or a for loop. It terminates the looping then transfers execution to the first statement after the loop.
continue Causes the looping to skip the rest of its body then moves to re-testing its condition again.
pass Does nothing, useful as a placeholder.

Example 2: break statement:


# Example 'break' statement

# A string will be copied to another string.
# The copy will be stopped if an 'n' is found.

str = 'This is a sentence'
strcopy = "'"
counter = 0
finished = len(str) - 1  # Strings are zero indexed

while (counter <= finished):
    s = str[counter]
    if (s == 'n'): break
    strcopy += s
    counter += 1

strcopy += "'"    
print('String copy is', strcopy) 

          
Output:

String copy is 'This is a se'

          

In the above example the loop is exited when the ‘n’ in ‘sentence’ is reached.

Example 3: continue statement:

# Example of a 'continue' statement

# A string will be copied to another string.
# The copy will be remove any
# double character combinations.

str = 'This is a sennnntence'
strcopy = "'"
prev = '' # empty string
counter = 0
finished = len(str) - 1  # Strings are zero indexed


while (counter <= finished):
    s = str[counter]
    # Check for double characters.
    # If a double character is found then ignore it.
    if (counter != 0 and prev == s):
        counter += 1
        continue
    strcopy += s
    counter += 1
    prev = s

strcopy += "'"    
print('String copy is', strcopy) 

          
Output:

String copy is 'This is a sentence'

          

In this code example the multiple n characters are removed.

Looping with while-else

An else block is added to the while statement. The else code is executed when the while condition becomes False. See FIG 2 which flowcharts this concept.

Python while-else Statement
FIG 2 - Python while-else Statement
Syntax

while <condition>:
  <loop body>
[else:
    <else body>]
          

Examples of the while-else statement:

The first example is rather trivial and nonsensical but demonstrates the order of code execution. The while code block cycles through 21 times before executing the else code.

Example 4

# Demonstrates looping with while-else

# A string will be copied to another string.
# The copy removes any double
# character combinations.

str = 'This is a sennnntence'
strcopy = "'"
counter = 0
# Strings are zero indexed
finished = len(str) - 1

while (counter <= finished):
    s = str[counter]
    # If double character found, ignore it
    if (counter != 0 and prev == s):
        counter += 1
        continue
    strcopy += s
    counter += 1
    prev = s
else: print('The "while" loop executed', counter, 'times')

strcopy += "'"    
print('String copy is', strcopy)
            
Output from the micro:bit

The "while" loop executed 21 times
String copy is 'This is a sentence'
            

It is important to note that if a break statement is executed in the while code block then if there is an else block it will be skipped.

Example 5A

# Demonstrates 'while-else' block behaviour
# if a 'break' statement is executed in 
# the 'while' block.

# A trivial example showing that an 'else' block
# will be skipped if the 'while' block executes
# a 'break' statement.

counter = 1
finish = 101
break_point = 90

while (counter != finish):
    pass  # do nothing!
    # The following condition guarantees that
    # the 'break' statement will be
    # executed eventually.
    if (counter == break_point): break
    counter += 1
else:
    # Since the 'break' statement is guaranteed
    # to eventually be executed, this 'else'
    # block will never run.
    print('While loop has successfully completed')
    
print('Program is ending...')
            
Output:

Program is ending...
            

It is clear that the else block has not executed. If the break statement is commented out (with #) then the else block will indeed be run:

Example 5B

counter = 1
finish = 101
break_point = 90

while (counter != finish):
    pass  # do nothing!
    # if (counter == break_point): break
    counter += 1
else:
    print('While loop has successfully completed')
    
print('Program is ending...')
            
Output:

While loop has successfully completed
Program is ending...
            

Endless Loops

Consider the following short Python program:

Example 6

# Example of an endless loop

counter = 1
while (5 != 4):
    pass  # Do nothing
    counter += 1
    print(counter)
    
print('Program is ending...')

          

In this example the final print statement will never be reached because 5 will never equal 4. Instead the program will continuously run the while code block till halted by an external event such as a keyboard interrupt.

For most computer programs this is an extremely undesirable turn of events. However there is one very good situation where an endless loop is deliberately used and that is where a microcontroller is involved.

Microcontrollers are embedded in all sorts of appliances, tools and equipment from kitchen gadgetry to cameras to weather stations and so. The list is endless.

As a simple example, a microcontroller embedded in a device might need to read a sensor, output the result to a small screen, wait a short period before repeating this cycle. This need to continue in an endless loop til the device is (e.g.) switched off.

Copy the following code into the MU Editor, save and flash to the micro:bit. Access the REPL to see the program's output.

Example 7: A Practical Endless Loop

# Demonstrates where an endless loop is useful.

# Digital temperature thermometer simulation
# run on a micro:bit.

# The micro:bit has an onboard temperature sensor
# which will be used to provide actual
# temperature readings.
# The readings are usually higher than ambient
# air temperatures because the sensor is
# affected by the interior temperature
# of the microcontroller.

# Library that provides methods to access
# hardware specific to the micro:bit.
import microbit

temp = None # Initial value
# Wait 2 seconds for the device to warm up
microbit.sleep(2000)

# Function to read the 
# micro:bit temperature sensor.
def ReadTemp():
    tempread = microbit.temperature()
    return tempread
    pass

# Function to validate the temperature read
def ValidTemp(temp):
   # Checks that the reading is an integer.
    return isinstance(temp, int)

# Function to write the temperature value.
# On a thermometer this would normally
# be a small LCD display.
def WriteTemp(temp):
    print('Temperature is', temp, 'degrees C')

# Main program loop, runs 'forever'!
while (5 != 4):
    temp = ReadTemp()
    if ValidTemp(temp):
        WriteTemp(temp)
    else: 
        WriteTemp('Err')
    # Wait 10 seconds before taking next reading.
    microbit.sleep(10000)

          
Output:

Temperature is 21 degrees C
Temperature is 21 degrees C
Temperature is 21 degrees C
Temperature is 21 degrees C
Temperature is 21 degrees C
Temperature is 21 degrees C
Traceback (most recent call last):
  File "main.py", line 47, in <module>
KeyboardInterrupt:     

          

This is an example of how a digital thermometer might work. The sensor chip is read. The value returned is checked for an error then written out to a small LCD display. The program waits 10 seconds then the read/write cycle is repeated.

This cycle of:

  • Read temperature
  • Validate temperature
  • Write temperature
  • Wait 10 seconds

will continue till it is externally interrupted e.g. the user switches the device off.

Nested Loops

Loops with while can be nested within each other to any practical depth. Care needs to be taken though that readability doesn't overly suffer.

The next program returns prime numbers. The first n primes are returned. Specifically the program has n = 15, but could be easily modified to accept a value that is input by a user.

Example 8

# Demonstrates a 'while' loop nested
# in another 'while loop.

# Returns the first 'n' prime numbers
# from a given starting point.

# Starting point for prime number search
num = 2
# Number of prime numbers required
n = 15
# Initialise prime numbers counter
count = 0

print('The first', n, 'prime numbers are:')

while (count < n):
    divisor = 2
    Prime = True
    while (num//2 >= divisor) and (Prime):
        # Check if num is divisible by anything
        # other than 1 or itself.
        if (num % divisor == 0): Prime = False
        divisor += 1
    if Prime: # Prime  number found
        print(num, end=' ') # Report the prime
        count += 1 # Increment the counter
    num += 1
    
print()
          
Output:

The first 15 prime numbers are:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
          

This program has a while loop nested in another while loop.

The outer loop keeps count of the number of prime numbers found and presents the next number to be checked for prime to the inner loop.

The inner loop checks if the current number (from the outer loop) is divisible by any number other than itself or 1.

The next tutorial in this series gives an example of a for loop nested within a while loop to solve the same prime numbers problem. The for loop makes the code simpler and hence easier to follow than the example above.