MicroPython Decision Making Statements

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:

Simple Decision Making with if

The if statement is the most simple form of decision-making statement. It takes an expression and checks if the expression evaluates to True then the block of code in the if statement will be executed.

If the expression evaluates to False, then the block of code is skipped.

Python if Statement
FIG 1 - Python if Statement
Syntax

if ( expression ):
    Statement 1
    Statement 2
    .
    Statement n

          

Note that the 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 MicroPython. The MicroPython language does not have a block end statement unlike many other languages.

Now for an example. This program while demonstrating the simple use of the if statement is very inefficient. A more efficient version would use a single if statement inside a for statement. The for looping statement is discussed here.

Example 1

# Simple 'if' statement example.

# It would be more efficient wrapping
# a single 'if' statement inside a 'for' statement,
# instead of using two 'if' statements.

str1 = 'BG'
List1 = ['A', 'B', 'C']
num = 0

print("Using two 'if' statements")
if (str1[0] in List1):
    print(str1[0], 'is in', List1)
    num += 1
print('Value of num:', num)

if (str1[1] in List1):
    print(str1[1], 'is in', List1)
    num += 1
print('Value of num:', num)
print()

print('\nProgram ending...')

          
Output:

Using two 'if' statements
B is in ['A', 'B', 'C']
Value of num: 1
Value of num: 1
Program ending...
          

Compound Decision Making with if−else

The if statement takes an expression and checks if the expression evaluates to True then the block of code in the if statement will be executed. If the condition evaluates to False then the block of code in the else statement will be executed instead.

An important point to make is only one of the block of codes will be executed. Execution will then drop down to the first statement following the if-else statement.

Python if-else Statement
FIG 2 - Python if-else Statement
Syntax

if ( expression ):
    Statement 1
    Statement 2
    .
    Statement n
else:
    Statement 1
    Statement 2
    .
    Statement n

          

Note again how the statements following if and else are indented.

Now for an example:

Example 2

# Demonstrates if-else statement

# Checks for a value in a list.
# Reports whether check value is found.
# Additionally, a code is returned.

# MicroPython library to generate random numbers
import random 

# Initial code is a random number
# between 1 and 9 inclusive.
code = random.randint(1, 9)

# Define the list to be searched.
# The list will have five members.
# Each member of the list is a
# random letter between 'A' and 'G'.
List1 = []
List1.append(chr(random.randint(65, 71)))
List1.append(chr(random.randint(65, 71)))
List1.append(chr(random.randint(65, 71)))
List1.append(chr(random.randint(65, 71)))
List1.append(chr(random.randint(65, 71)))

# We will look for this value in the list.
check = 'G'

print('Initial code is:', code)
print('Searching for:', check)

# If 'check' value is found in the list
# then the code is incremented by 1,
# otherwise the code is decremented by 1.
if (check in List1):
    print(check, 'is in', List1)
    code += 1
else:
    print(check, 'is not in', List1) 
    code -= 1

print('Result code is:', code)
          
Typical Output from the micro:bit

Initial code is: 6
Searching for: G
G is in ['B', 'E', 'A', 'G', 'C']
Result code is: 7
          

The list (List1) is populated with five randomly generated elements (between "A" and 'G"). Whether the if block of code or the else block of code is executed will depend upon these randomly generated list element values and cannot be predicted before the program executes.

Complex Decision Making with if−elif−else

The elif keyword allows multiple conditions to be chained together. From the top, each condition is evaluated and the first one that is True has its code block executed. If none of the conditions are found to be True then, if it is present, the optional else block will have its code executed.

Again it is important to note that while there may be numerous code blocks only one at most will ever be executed. Execution will then drop down to the first statement following the if-elif-else statement.

Python if-elif-else Statement
FIG 3 - Python if-elif-else Statement
Syntax

if ( expression ):
    Statement 1
    Statement 2
    .
    Statement n
elif ( expression 1 )
    Statement 1
    Statement 2
    .
    Statement n
elif ( expression 2)
    Statement 1
    Statement 2
    .
    Statement n
.
.
elif ( expression n)
    Statement 1
    Statement 2
    .
    Statement n
[else:
    Statement 1
    Statement 2
    .
    Statement n]

          

While the block indentation is mandatory in MicroPython it is also very important for readability as the complexity of the decision making statement increases.

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

Example 3

# Demonstrates if-elif-else statement.

# Checks for a value sequentially in three lists.
# Returns the values of the first list
# where the check value is found.
# Additionally, a code is returned.

# MicroPython library; generates random numbers
import random

# Initial code is a random number
# between 1 and 9 inclusive.
code = random.randint(1, 9)

List1 = ['A', 'B', 'C', 'D']
List2 = ['E', 'F', 'G', 'H']
List3 = ['I', 'J', 'K', 'L']

# Generates a random letter in 'A' to 'Z' range.
# We will look for this value in the three lists.
check = chr(random.randint(65, 90))

print('Initial code is:', code)
print('Searching for: ', check)

if (check in List1):
    print(check, 'is in', List1)
    code += 1
elif (check in List2):
    print(check, 'is in', List2)
    code += 2
elif (check in List3):
    print(check, 'is in', List3)
    code += 3
else:
    print(check, 'is not in any list') 
    code -= 1

print('Result code is:', code)
          

If this code has been run on the micro:bit the REPL output will look like this:

Typical Output from the micro:bit

Initial code is: 9
Searching for:  E
E is in ['E', 'F', 'G', 'H']
Result code is: 11
          

Which if-elif-else code block is executed depends on the value of check which is a randomly generated uppercase letter.

Nested if Statements

An excellent definition of nested if statements can be found at techvidvan.com

In very simple words, nested if statements is an if statement inside another if statement. Python allows us to stack any number of if statements inside the block of another if statements. They are useful when we need to make a series of decisions.

MicroPython doesn't have the C/C++ switch-case statement so relies exclusively on if-elif-else. Care needs to be taken with nesting if-elif-else statements. Complicated decision making structures can quickly lead to overly convoluted logic that becomes difficult to follow and debug.

Example 4

# Demonstrates nested if statements.

# Standard MicroPython library; generates random numbers
import random 

# Generate a random number between 1 and 4
num_major = random.randint(0,4)

# Generate a random integer 1 or 2
num_minor = random.randint(1, 2)

print('Major number =', num_major)
print('Minor number =', num_minor)

if (num_major == 1):
    print('Success on first attempt!')
    if (num_minor == 1): 
        num_minor = 10
    else: 
        num_minor = -10
elif (num_major == 2):
    print('Success on second attempt!')
    if (num_minor == 1): 
        num_minor = 100
    else: 
        num_minor = -100
elif (num_major == 3):
    print('Success on third attempt!')
    if (num_minor == 1): 
        num_minor = 1000
    else: 
        num_minor = -1000
else:
    # num_major == 4
    print('Success on fourth attempt!')
    if (num_minor == 1): 
        num_minor = 10000
    else: 
        num_minor = -10000

print('Minor number final value:', num_minor)

          

This is a fairly nonsensical example but does show what can be done with nesting. There is an if-else statement code block nested inside each if, elif and else block.

The output will depend upon the random numbers that are assigned to num_major and num_minor.

Sample Output from the micro:bit

Major number = 4
Minor number = 1
Success on fourth attempt!
Minor number final value: 10000

          

Ternary Selection

Ternary selection provides a means to code a simple if-else on a single line. The syntax is simple.

Syntax

X if (condition) else Y

          

If the condition is True then X is returned. If the condition is False then Y is returned.

Example 5

# Demonstrates ternary selection.

# The program returns the larger of two numbers.

# Standard MicroPython library; generates random numbers.
import random

# Random numbers between 1 and 99
num1 = random.randint(1, 99)
num2 = random.randint(1, 99)

# Using ternary selection to find largest number.
max = num1 if (num1 >= num2) else num2
print('num1 =', num1)
print('num2 =', num2)
print('max =', max)

          

Again the output will depend upon the random numbers assigned to variables num1 and num2. A typical output generated when run on a micro:bit is shown below:

Sample Output:

num1 = 31
num2 = 29
max = 31