MicroPython Statements and Blocks

Contents

Introduction

This is a series exploring the MicroPython language. The MU Editor and IDE will be used to develop the code which will be flashed and executed on a BBC micro:bit.

These tutorials will only explore the "pure" syntax of the language i.e. no device specific library functions aimed at the micro:bit (such as reading and writing to GPIO ports) will be used.

These series of MicroPython tutorials assume some coding familiarity in another programming language such as C++.

A short tutorial can be found here for those unfamiliar with the Mu Editor and how it is used to program the micro:bit.

Statements

A statement is an instruction that the MicroPython interpreter can execute. So, in simple words, anything written in MicroPython is a statement. MicroPython statements generally end at the line end.

Example 1


a = 5
b = 6
c = 7
d = a + b +c
print('The answer is', d)
          

Copy the above code snippet, save as a file then flash the micro:bit. The REPL panel will display the program's output.

Output:


The answer is 18 
          

Multiple statements can be given on a line using ; as the statement terminator. However this practice is generally frowned upon.


a = 5; b = 6; c = 7; d = a + b +c; print('The answer is', d)
          

Blocks

A block is a piece of MicroPython program that is executed as a unit. Blocks containing multiple lines of code are defined by indentation. The examples below use the if keyword which is one of MicroPython's decision control statements. Its usage is discussed here.

Consider the following code block:

Example 2


x=5
y=2
if x > y:
    temp = x
    x = y
    y = temp
    
print ("x=", x, " y=", y)
          

Lines 3, 4, 5, 6 are a block. Note how lines 4, 5, 6 are indented relative to line 3. It is this indentation that defines the block. While assignment and conditional statements will be covered in future articles, it should be obvious that this small program will swap the values of x and y if the value of x is greater than the value of y. The program's REPL output is shown below.

Output:


x= 2  y= 5
        

A block in the simplest of cases may also exist as a single line of code:


if x > y: print(x)
        

Comments

Comments are an integral part of any program code. Comments are easy to insert into MicroPython code. Anything after the hash character (#) is ignored. Blank lines (white space) may also be inserted between lines of code to improve readability


# This program swaps two numbers around
# Author: Fred's Cave
a = 10
b = 5

# Output initial values
print('Initial values:', a, ',', b)

# Now to do the swap
temp = a  #Temporary placeholder
a = b
b = temp

# Output swapped values
print('Swapped value:', a, ',', b)
        

Output:


Initial values: 10 , 5
Swapped value: 5 , 10